c - 如何在 Linux 中使用 gethostbyname_r

标签 c linux sockets network-programming

我目前使用的是线程不安全的 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/

相关文章:

c - Valgrind: "Conditional jump or move depends on uninitialised value(s)"

c - 如果声明了 union,循环将不会显示

C HTTP Proxy,浏览器无限期显示 "waiting for"

Java 套接字 - 自定义对象发送

c - memcpy 在不同的编译器中给出不同的输出

python - 在第一原则级别将 float 转换为 bool 值或从 bool 值转换时会发生什么?

linux - 如何从 Linux ls 或 find 命令的文件列表中获取内容

linux - 如果存在另一行,则 Bash 替换行

linux - 使用 cgroup 限制 IO 使用

c - 数据包重传