getaddrinfo错误地解析主机名

时间:2015-01-25 10:21:29

标签: c++ linux networking getaddrinfo

我尝试使用getaddrinfo函数(http://man7.org/linux/man-pages/man3/getaddrinfo.3.html)来获取IP地址的in_addr结构,但据我所知,出了点问题,或者我做错了什么。请考虑以下代码段。

bool resolve_host (string hostname, in_addr* address) {
    cout << "hostname  = " << hostname << endl;
    addrinfo *res {};

    addrinfo hints {0, AF_INET, 0, 0, 0, nullptr, nullptr, nullptr};

    auto result = getaddrinfo (hostname.c_str (), nullptr, &hints, &res);
    if (!result) { 
        memcpy (address, &((struct sockaddr_in*) res->ai_addr)->sin_addr, sizeof (in_addr));
        freeaddrinfo (res);

        cout << "resolved addr = " << inet_ntoa (*address) << endl << endl;

        return true;
    }
    else {
        return false;
    }
}

使用如下:

in_addr addr {};
resolve_host ("www.google.pl", &addr);      // 1
resolve_host ("linux-1smb", &addr);         // 2
resolve_host ("192.168.100.100", &addr);    // 3
resolve_host ("192.168.100.1001", &addr);   // 4

resolve_host ("wrong_name", &addr);         // 5

输出如下:

hostname  = www.google.pl
resolved addr = 74.125.71.94

hostname  = linux-1smb
resolved addr = 192.168.0.101

hostname  = 192.168.100.100
resolved addr = 192.168.100.100

hostname  = 192.168.100.1001
hostname  = wrong_name
resolved addr = 217.74.65.145

前四个电话的行为与预期相符。当然假设linux-1smb是一个已知的主机名(添加到/ etc / hosts)。但最后一次(5)调用显示主机名&#34; wrong_name&#34; (当然没有添加到/ etc / hosts中)的IP地址为217.74.65.145。

你能告诉我哪里有错误(在代码中,或者了解getaddrinfo是如何工作的)?

/ etc / hosts的内容是:

#
# hosts         This file describes a number of hostname-to-address
#               mappings for the TCP/IP subsystem.  It is mostly
#               used at boot time, when no name servers are running.
#               On small systems, this file can be used instead of a
#               "named" name server.
# Syntax:
#    
# IP-Address  Full-Qualified-Hostname  Short-Hostname
#

127.0.0.1       localhost 

# special IPv6 addresses
::1             localhost ipv6-localhost ipv6-loopback

fe00::0         ipv6-localnet 

ff00::0         ipv6-mcastprefix 
ff02::1         ipv6-allnodes 
ff02::2         ipv6-allrouters 
ff02::3         ipv6-allhosts 
192.168.0.101   linux-1smb 
225.0.0.37      multi-test 

如果我改变提示,值得提及的是:

addrinfo hints {0, AF_UNSPEC, 0, 0, 0, nullptr, nullptr, nullptr};

(据我所知 - 来自文档)等于:

getaddrinfo (hostname.c_str (), nullptr, nullptr, &res);

第四次通话的结果是:

hostname  = 192.168.100.1001
resolved addr = 217.74.65.145

与呼叫5的情况相同,IP地址相同。

可能的解决方案:

我在评论中读到了一些可能的情况,我检查了一下。事实证明,地址217.74.65.145是我的ISP的地址,它基本上将所有未知的主机名(例如来自浏览器)转发到此地址。我想,这就是getaddrinfo返回此地址的原因。我仍然不知道如何解决这个问题,但现在我知道为什么会这样。

由于

0 个答案:

没有答案
相关问题