Mail Archives: cygwin/2004/05/07/11:56:13
i'm using gethostname in a multithreaded code ando sometimes i get error. i
think it's not a bug of my code (and i post it) because it does not happed
always, but sometimes.
maybe gethostname() thread-unsafe?
the code:
in_addr_t get_my_IP()
{
char name[255]; //store my hostname (hostname are limited to 255chars)
struct hostent * hostent_ptr = NULL;
in_addr_t iserror = 0;
int ret;
ret = gethostname (name, 255);
if(ret == -1) {
printf ("ERROR gethostname() failed, Errno=%d \nDescription: %s\n", errno,
strerror(errno));
iserror = 1;
}
hostent_ptr = gethostbyname(name);
if(hostent_ptr == NULL)
{
printf ("ERROR gethostbyname() failed, h_errno=%d \nDescription: %s\n",
h_errno, hstrerror(h_errno));
iserror = 1;
}
if (iserror == 0) {
//h_addr_list contains IPs of this host in network byte order
return ((struct in_addr *)hostent_ptr->h_addr_list[0])->s_addr;
//get the first IP.
} else { // use getsockname() technique
return get_my_ip_getsockname();
}
}
in_addr_t get_my_ip_getsockname()
{
int socketfd;
struct sockaddr_in local;
socklen_t socklen;
int ret;
/* get a datagram socket (UDP)) */
socketfd = socket(AF_INET, SOCK_DGRAM, 0);
if (socketfd == -1) {
printf("ERROR socket() failed, Errno= %d\nDescription: %s\n",errno,
strerror(errno));
return 0;
}
memset(&local, 0, sizeof(local));
socklen = sizeof(local);
ret = getsockname(socketfd, (struct sockaddr *)&local, &socklen);
if (ret == -1) {
printf("ERROR getsockname() failed, Errno=%d\nDescription: %s\n",
errno, strerror(errno));
return 0;
}
close(socketfd);
return local.sin_addr.s_addr;
}
THE ERROR IS:
ERROR gethostbyname() failed, h_errno=-1
Description: (null)
ERROR socket() failed, Errno= 1
Description: Operation not permitted
ERROR Aggregation: get_my_IP() failed
--
Unsubscribe info: http://cygwin.com/ml/#unsubscribe-simple
Problem reports: http://cygwin.com/problems.html
Documentation: http://cygwin.com/docs.html
FAQ: http://cygwin.com/faq/
- Raw text -