我有一个Raspberry Pi,它在Python的getaddrinfo中存在名称解析问题。我可能是错误地将源代码跟踪到了C函数gethostbyaddr。因此,现在我试图创建一个简单的测试以查看该函数返回的结果。套接字编程和C困扰着我,但是我的尝试是:

#include <sys/socket.h>
#include <string.h>
#include <stdio.h>

static struct gai_afd {
    int a_af;
    int a_addrlen;
    int a_socklen;
    int a_off;
    const char *a_addrany;
    const char *a_loopback;
};

int main()
{
  struct hostent *hp;
  struct gai_afd *gai_afd;
  hp = gethostbyaddr("google.com", gai_afd->a_addrlen, AF_INET);
}

使用gcc进行编译会给出两个警告:
warning: useless storage class specifier in empty declaration [enabled by default]
In function ‘main’: warning: assignment makes pointer from integer without a cast [enabled by default]

运行a.out会产生段错误。

为了使上述工作有效,我必须更改什么?

我的目标是找出为什么ping可以在同一台计算机上正常运行时getaddrinfo无法解析google.com。我面临的麻烦是here

最佳答案

指针未初始化。

至少

int main()
{
  struct hostent *hp;
  struct gai_afd *gai_afd = malloc(sizeof(gai_afd));

  // ...

}

这是一个查找信息的小例子:
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    int i;
    struct hostent *he, *inner_he;
    struct in_addr **addr_list;
    unsigned long ip;
    char *addressString;

    if (argc != 2) {
        fprintf(stderr,"usage: ghbn hostname\n");
        return 1;
    }

    if ((he = gethostbyname(argv[1])) == NULL) {  // get the host info
        herror("gethostbyname");
        return 2;
    }

    // print information about this host:
    printf("Official name is: %s\n", he->h_name);
    addr_list = (struct in_addr **)he->h_addr_list;
    for(i = 0; addr_list[i] != NULL; i++)
    {
        addressString = inet_ntoa(*addr_list[i]);

        printf("    IP addresse %d: %s \n", i, addressString);

        ip = inet_addr(addressString);

        inner_he = gethostbyaddr((const char *)&ip, sizeof(ip), AF_INET);
        if (inner_he != NULL)
            printf("Host name: %s\n", inner_he->h_name);
    }
    printf("\n");

    return 0;
}

您可以通过www.usa.com启动它,输出将是:
Official name is: www.usa.com
    IP addresse 0: 69.10.42.209
Host name: lawyer.com

09-25 21:19