开发者

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜