c - gethostbyname 失败,主机名来自 gethostbyaddr,成功了

标签 c networking gethostbyname gethostbyaddr

我有以下脚本:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>

const char *ip="190.162.1.2";

int main(int argc, const char * argv[])
{
    in_addr host_addr;
    hostent *addr=0;
    hostent *host=0;
    inet_pton(AF_INET, ip, &host_addr);
    addr=gethostbyaddr(&host_addr, sizeof(host_addr), AF_INET);
    printf("gethostbyaddr(%s):\n",ip);
    if(!addr)
        herror("Unable to resolve host by address");
    else {
        printf(" OK\n");
        host=gethostbyname(addr->h_name); //use the hostname we got previously
        printf("gethostbyname(%s):\n",addr->h_name);
        if(!host){
            herror(" Unable to resolve host by name"); //gets here, why?
            return 0;
        } else {
            printf(" IP addresses of %s: \n",addr->h_name);
            in_addr **addr_list;
            addr_list = (in_addr **)host->h_addr_list;
            for(int i = 0; addr_list[i] != NULL; i++) {
                printf("%s \n", inet_ntoa(*addr_list[i]));
            }
        }
    }
    return 0;
}

而且我想知道为什么 gethostbyname 会因先前成功的 gethostbyaddr 的主机名而失败。谁能解释一下为什么?

进度:

gethostbyaddr(190.162.1.2):
 OK
gethostbyname(pc-2-1-162-190.cm.vtr.net):
 Unable to resolve host by name: Unknown host

但它适用于其他 IP 地址,如 173.194.34.129 (google.com) 等。

最佳答案

您的 DNS 服务器的本地配置可能有错误。 DNS 具有双向映射(IP 到主机名和主机名到 IP);看起来后者不见了。

让您的系统管理员检查一下。

如果您从命令行使用主机名 ping 主机,它会显示 IP 地址吗?

关于c - gethostbyname 失败,主机名来自 gethostbyaddr,成功了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22696929/

相关文章:

c - DWARF 行表中的源列号

c++ - Valgrind 调试结果不显示发生错误的行数

c++ - gethostbyname 函数中的 IP 地址顺序

c++ - 从URL获取IP(C++)

java - 使用scala获取当前机器的公共(public)IP地址

c++ - gethostbyname 中的 malloc_consolidate 出现段错误

c - 使用cygwin在windows下构建libevent?

c - while 循环中的 printf 打印两次而不是一次

c - 你如何处理未知数量的命令行参数?

Docker 统计网络流量