How to use gethostbyname_r in linux
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6517478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use gethostbyname_r in linux
提问by harry
I am currently using thread unsafe gethostbynameversion 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.
I am currently using thread unsafe gethostbynameversion 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_rmethod ? any ideas ? How to use it and how to handle its error conditions if any.
Has anybody used this gethostbyname_rmethod ? any ideas ? How to use it and how to handle its error conditions if any.
采纳答案by cnicutar
The function is using a temporary buffer supplied by the caller. The trick is to handle the ERANGE
error.
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
EDIT
In light of recent comments I guess what you really want is getaddrinfo
.
In light of recent comments I guess what you really want is getaddrinfo
.