首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Linux网络(gethostbyaddr)

Linux网络(gethostbyaddr)
EN

Stack Overflow用户
提问于 2015-02-17 16:40:25
回答 1查看 8.5K关注 0票数 0

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

代码语言:javascript
复制
#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;
}

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

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

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-17 17:54:04

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

例如,下面的代码,如果没有您使用的不推荐的函数,则会给出结果host=google-public-dns-a.google.com,而使用主机地址则会给出could not resolve hostname

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

以下是代码:

代码语言:javascript
复制
#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;                                                  
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28566424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档