【问题标题】:Which header file to include for the use of gethostbyname_r() function使用 gethostbyname_r() 函数需要包含哪个头文件
【发布时间】:2015-01-27 12:03:10
【问题描述】:

我在代码中使用gethostbyname_r() 函数,编译时出现以下错误。

gethostname.cpp:17: 错误:'gethostbyname_r' 未在此范围内声明

我的代码:

#include<stdio.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/file.h>
int main()
{
  struct hostent hostbuf;
 struct hostent *hp = NULL;
 char* hostent_buff;
 int herr = 0;
 int hres = 0;

 hres = gethostbyname_r("domain name", &hostbuf,
 hostent_buff, 1024, &hp, &herr);

 if (NULL == hp)
 {
 return -1;
 }

  return 0;
}

谁能帮助我? 我可以在 Linux 和 Solaris 上使用相同的函数 gethostbyname_r() 吗?

【问题讨论】:

  • 只是好奇,为什么你的文件名为gethostname.cpp?请问你用的是什么编译器?
  • 另请注意,gethostbyname_r 是 GNU 扩展,而不是标准的 C 库函数。
  • 另请注意,现代代码应使用getnameinfogetaddrinfo 代替
  • 错误信息还有更多内容吗?也许是签名不匹配?根据我的手册页,你有正确的#includes。
  • @Sourav gethostname.c 也无法获取 ld: Unsatisfied symbol "gethostbyname_r" in file /var/tmp//ccLwNIet.o

标签: c linux networking


【解决方案1】:

简答:

#define _BSD_SOURCE
#include <netdb.h>

#define _SVID_SOURCE
#include <netdb.h>

更长的答案:

这不是 POSIX 函数。你问的是Linux。根据手册页,你想要

#include <netdb.h>

以及以下功能测试宏:

glibc 的功能测试宏要求(请参阅feature_test_macros(7)):

  gethostbyname2(), gethostent_r(), gethostbyaddr_r(), gethostbyname_r(),
   gethostbyname2_r():
       _BSD_SOURCE || _SVID_SOURCE

在我的系统上确认这一点,/usr/include/netdb.h 包含:

extern int gethostbyname_r (const char *__restrict __name,
                            struct hostent *__restrict __result_buf,
                            char *__restrict __buf, size_t __buflen,
                            struct hostent **__restrict __result,
                            int *__restrict __h_errnop);

但是,这是有条件的

#ifdef __USE_MISC

这可能意味着您既没有定义_BSD_SOURCE 也没有定义_SVID_SOURCE,这是获得定义所必需的。

来自features.h

 __USE_MISC           Define things common to BSD and System V Unix.

然后:

#if defined _BSD_SOURCE || defined _SVID_SOURCE
# define __USE_MISC     1
#endif

【讨论】:

  • 我可以在 Linux 和 Solaris 上使用相同的函数 gethostbyname_r() 吗?
猜你喜欢
  • 2011-04-14
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
相关资源
最近更新 更多