要包含哪个头文件以使用gethostbyname_r()函数

时间:2015-01-27 12:03:11

标签: c linux networking

我在我的代码中使用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()吗?

1 个答案:

答案 0 :(得分: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
相关问题