-1

gethostbyname在 Fedora 32 位中工作正常,但在 64 位环境中失败,导致分段错误?在这种情况下,问题是什么,我们该如何解决?

#include <stdio.h>  
#include <string.h>  
#include <netdb.h>  
#include <netinet/in.h>  

struct hostent *he;  
struct in_addr a; 

int main (int argc, char **argv)  {  

    if (argc != 2)  {  
        fprintf(stderr, "usage: %s hostname\n", argv[0]);  
        return 1;  
    }  

    he = gethostbyname (argv[1]);  
    if (he)  {  
        printf("name :- %s\n", he->h_name);  
        while (*he->h_aliases)  
            printf("alias:- %s\n", *he->h_aliases++);  
        while (*he->h_addr_list)  {  
            bcopy(*he->h_addr_list++, (char *) &a, sizeof(a));  
            printf("address:- %s\n", inet_ntoa(a));  
        }  
    }  
    else  
        herror(argv[0]);  
    return 0;  
}
4

1 回答 1

2

您缺少正确的包括:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

如果没有正确的包含,inet_ntoa则假定返回类型为int. 因为与 x86 上int的大小相同char*,所以没有问题。在 x86_64 上并非如此,因此读取该字符串printf会导致错误。

于 2012-07-19T13:40:58.203 回答