gethostbyname因gethostbyaddr的主机名失败而成功

时间:2014-03-27 19:07:20

标签: 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)等。

1 个答案:

答案 0 :(得分:0)

您的DNS服务器的本地配置可能有错误。 DNS在两个方向都有映射(IP到主机名,主机名到IP);看起来后者不见了。

让系统管理员检查一下。

如果使用命令行中的主机名ping主机,它是否显示IP地址?