在c中使用gethostbyname()检索主机的真实IP地址的正确方法是什么?人们为什么还会说DHCP会使这种方法面临潜在危险?
最佳答案
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...
}
}
关于c - 使用gethostbyname()查找IP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30068938/