gpt4 book ai didi

c - 如何在 Linux 中使用 gethostbyname_r

转载 作者:IT王子 更新时间:2023-10-29 01:24:54 26 4
gpt4 key购买 nike

我目前使用的是线程不安全的 gethostbyname 版本,它非常易于使用。你传递主机名,它返回给我地址结构。看起来在 MT 环境中,此版本使我的应用程序崩溃,因此尝试将其替换为 gethostbyname_r。发现很难用谷歌搜索示例用法或任何好的文档。

有人用过这个gethostbyname_r方法吗?有任何想法吗 ?如何使用它以及如何处理它的错误情况。

最佳答案

该函数正在使用调用者提供的临时缓冲区。诀窍是处理 ERANGE 错误。

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");
}

编辑

根据最近的评论,我猜你真正想要的是 getaddrinfo .

关于c - 如何在 Linux 中使用 gethostbyname_r,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6517478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com