【问题标题】:How to use gethostbyname_r in linux如何在 Linux 中使用 gethostbyname_r
【发布时间】:2011-09-24 22:32:26
【问题描述】:

我目前正在使用线程不安全 gethostbyname 版本,该版本非常易于使用。您传递主机名,它会返回地址结构。看起来在 MT 环境中,这个版本使我的应用程序崩溃,所以试图用 gethostbyname_r 替换它。发现很难用谷歌搜索示例用法或任何好的文档。

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

【问题讨论】:

标签: c linux sockets network-programming


【解决方案1】:

函数正在使用调用者提供的临时缓冲区。诀窍是处理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");
}

编辑

鉴于最近的 cmets,我猜你真正想要的是 getaddrinfo

【讨论】:

  • 谢谢!你知道如何派生我需要传递给套接字连接调用的 server_addr.sin_addr 吗?
  • @harry 查看我编辑的答案。如果您没有收到getaddrinfo(或根本不喜欢它),请再问一个问题。
  • 虽然很少见,但是将realloc的返回值赋给原来的指针变量可能会导致内存泄漏。
  • @felix021 为什么会这样?我没看到。
  • 在 realloc 调用中的 buflen 应该是 len。 @eduardo 是正确的,realloc 在这里使用正确,但应该指出,在某些时候 buf 在使用后需要 free()d。
猜你喜欢
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2014-09-15
相关资源
最近更新 更多