Linux网络(gethostbyaddr)

时间:2015-02-17 16:40:26

标签: c linux network-programming

我正在尝试获取有关IP地址 89.249.207.231 的主机的主机信息。我知道它存在,因为当我在浏览器的url字段中键入IP地址时,它会找到该页面。这是我在C中的代码。

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>

int main()
{
    struct in_addr addr;
    inet_aton("89.249.207.231", &addr);
    struct hostent* esu = gethostbyaddr((const char*)&addr),sizeof(addr), AF_INET);
    printf("%s\n", esu->h_name);
    return 0;
}

当我编译并运行它时,它会给出“分段错误”。我无法理解代码的问题。

任何提示和建议都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:3)

即使主机存在,也没有必要提取其主机名。

例如,以下代码,如果没有您使用的已弃用函数,则会得到结果host=google-public-dns-a.google.com,而您的主机地址则为could not resolve hostname

您的段错误的原因是esuNULL,因为该函数无法通过给定的IP解析主机名。

以下是代码:

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

int main()
{
    struct sockaddr_in sa;    /* input */
    socklen_t len;         /* input */
    char hbuf[NI_MAXHOST];

    memset(&sa, 0, sizeof(struct sockaddr_in));

    /* For IPv4*/
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = inet_addr("8.8.8.8");
    len = sizeof(struct sockaddr_in);

    if (getnameinfo((struct sockaddr *) &sa, len, hbuf, sizeof(hbuf), 
        NULL, 0, NI_NAMEREQD)) {
        printf("could not resolve hostname\n");
    }
    else {
        printf("host=%s\n", hbuf);
    }

    return 0;                                                  
}