Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use gethostbyname_r in linux

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.

like image 672
harry Avatar asked Jun 29 '11 08:06

harry


People also ask

Does Gethostbyname use DNS?

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.

What is Gethostbyname C?

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.

What is get host by name?

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.

What is Hostent?

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.


1 Answers

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.

like image 58
cnicutar Avatar answered Oct 04 '22 05:10

cnicutar