Linux 网络(gethostbyaddr)

Linux networking (gethostbyaddr)

我正在尝试获取有关 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;
}

当我编译并 运行 它时,它给出 "Segmentation fault"。我无法理解我的代码的问题。

如有任何提示和建议,我们将不胜感激。

谢谢!

即使主机存在,您也可能无法提取其主机名。

例如,以下代码在不使用您使用的已弃用函数的情况下给出结果 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;                                                  
}