简体   繁体   English

gethostbyname在OSX(Yosemite 10.10.4)上失败

[英]gethostbyname fails on OSX (Yosemite 10.10.4)

"gethostbyname" returns a pointer to this structure: “ 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 */
 };

When I try to use it, h_name points to a valid string: the partial name I supply is expanded to the correct fully qualified host name. 当我尝试使用它时,h_name指向一个有效的字符串:我提供的部分名称将扩展为正确的标准主机名。

The value of h_addr_list is 4 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.

I'm running a 32 bit process (MS Office), the h_name pointer is a valid 32 bit pointer. 我正在运行32位进程(MS Office),h_name指针是有效的32位指针。 WTF am I doing wrong? WTF我做错了吗? Does gethostbyname work for other people, or on other versions of OSX? gethostbyname是否可用于其他人或在OSX的其他版本上使用?

I was able to run this small example successfully on 10.10.4 (taken from paulschreiber.com ) 我能够在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");
    }
}

However, it did segfault on 64-bit without #include <arpa/inet.h : without that, no prototype for inet_ntoa is found, the return type is assumed to be an int (when it's actually a char * ), and on 64-bit this truncates the pointer and causes a segfault. 但是,它确实在没有#include <arpa/inet.h情况下在64位上进行了段错误:如果没有,则找不到inet_ntoa原型,返回类型假定为int (实际上是char * ),在64位上-bit这会截断指针并导致段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM