OSX上的gethostbyname失败(Yosemite 10.10.4)

时间:2015-08-12 05:25:54

标签: macos network-programming

"的gethostbyname"返回指向此结构的指针:

 struct  hostent {
         char    *h_name;        /* official name of host */
         char    **h_aliases;    /* alias list */
         int     h_addrtype;     /* host address type */
         int     h_length;       /* length of address */
         char    **h_addr_list;  /* list of addresses from name server */
 };

当我尝试使用它时,h_name指向一个有效的字符串:我提供的部分名称被扩展为正确的完全限定主机名。

h_addr_list的值是4

h_name is valid
h_aliasis is a valid pointer to a null pointer
h_addrtype is 2 (AF_INET, IPV4)
h_length is 0 (should be 4, or perhaps a multiple of 4)
h_addr_list is 4, fails when dereferenced.

我正在运行32位进程(MS Office),h_name指针是一个有效的32位指针。 WTF我做错了吗? gethostbyname是否适用于其他人或其他版本的OSX?

1 个答案:

答案 0 :(得分:0)

我能够在10.10.4(取自paulschreiber.com

上成功运行这个小例子
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>

int main(int argc, char **argv) {
    if (argc < 2) {
        printf("Usage: %s hostname", argv[0]);
        exit(-1);
    }

    struct hostent *hp = gethostbyname(argv[1]);

    if (hp == NULL) {
       printf("gethostbyname() failed\n");
    } else {
       printf("%s = ", hp->h_name);
       unsigned int i=0;
       while ( hp -> h_addr_list[i] != NULL) {
          printf( "%s ", inet_ntoa( *( struct in_addr*)( hp -> h_addr_list[i])));
          i++;
       }
       printf("\n");
    }
}

然而,它在没有#include <arpa/inet.h的情况下对64位进行了段错误:没有它,没有找到inet_ntoa的原型,返回类型被假定为int(当它实际上是一个char *),在64位上,这会截断指针并导致段错误。