0

在 c 中使用 gethostbyname() 来检索主机的真实 IP 地址的正确方法是什么。另外,为什么人们会说 DHCP 会使这种方法处于潜在危险之中?

4

1 回答 1

0

gethostbyname()函数通过使用 DNS 查找名称来返回有关主机的信息。

该函数的返回数据类型和参数如下所示:

struct hostent* gethostbyname(const char *name);

从主机名(在本例中为“mail.google.com”)提取 IP 地址列表的示例如下所示:

char host_name = "mail.google.com";
struct hostent *host_info = gethostbyname(host_name);

if (host_info == NULL) 
{
    return(-1);
}

if (host_info->h_addrtype == AF_INET)
{
    struct in_addr **address_list = (struct in_addr **)host_info->h_addr_list;
    for(int i = 0; address_list[i] != NULL; i++)
    {
        // use *(address_list[i]) as needed...
    }
}
else if (host_info->h_addrtype == AF_INET6)
{
    struct in6_addr **address_list = (struct in6_addr **)host_info->h_addr_list;
    for(int i = 0; address_list[i] != NULL; i++)
    {
        // use *(address_list[i]) as needed...
    }
}
于 2015-05-06T08:06:57.397 回答