harry
harry

Reputation: 1081

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.

Upvotes: 6

Views: 14408

Answers (1)

cnicutar
cnicutar

Reputation: 182609

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.

Upvotes: 7

Related Questions