C - 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(" OKn");
        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地址?

相关内容

  • 没有找到相关文章

最新更新