套接字编程故障排除

3

我有一个树莓派,使用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会出现“分段错误”。

我需要做出哪些改变才能使上述工作正常?

我的目标是找出为什么getaddrinfo无法解析google.com,而ping在同一台机器上却可以正常工作。我遇到的问题在这里

2个回答

2
指针没有初始化。
至少。
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

0

你没有为你的结构体分配任何内存,并且解引用了一个未初始化的指针


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接