排除套接字编程

时间:2016-01-28 08:03:22

标签: c sockets networking network-programming

我有一个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会出现Segmentation fault。

为了完成上述工作,我必须做些什么改变?

我的目标是找出为什么getaddrinfo无法解决google.com,当ping在这台机器上工作正常时。我面临的问题是here

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您没有为结构分配任何内存,并取消引用未初始化的指针