I am currently using thread unsafe gethostbyname version which is very easy to use. You pass the hostname and it returns me the address structure. Looks like in MT environment, this version is crashing my application so trying to replace it with gethostbyname_r. Finding it very difficult to google a sample usage or any good documentation.
Has anybody used this gethostbyname_r method ? any ideas ? How to use it and how to handle its error conditions if any.
The GetHostByName method queries the Internet DNS server for host information. If you pass an empty string as the host name, this method retrieves the standard host name for the local computer.
The SAS/C implementation of gethostbyname is a combination of the host file and resolver versions of the BSD UNIX Socket Library gethostbyname function. EXAMPLE. This program uses the socket call, gethostbyname to return an IP address that corresponds to the supplied hostname.
The gethostbyname function returns a pointer to a hostent structure—a structure allocated by Windows Sockets. The hostent structure contains the results of a successful search for the host specified in the name parameter.
The hostent structure is used by functions to store information about a given host, such as host name, IPv4 address, and so forth. An application should never attempt to modify this structure or to free any of its components.
The function is using a temporary buffer supplied by the caller. The trick is to handle the ERANGE
error.
int rc, err;
char *str_host;
struct hostent hbuf;
struct hostent *result;
while ((rc = gethostbyname_r(str_host, &hbuf, buf, len, &result, &err)) == ERANGE) {
/* expand buf */
len *= 2;
void *tmp = realloc(buf, buflen);
if (NULL == tmp) {
free(buf);
perror("realloc");
}else{
buf = tmp;
}
}
if (0 != rc || NULL == result) {
perror("gethostbyname");
}
EDIT
In light of recent comments I guess what you really want is getaddrinfo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With