作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我目前使用的是线程不安全的 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/
我是一名优秀的程序员,十分优秀!