我正在尝试构建一个工具来根据域名收集有关IP地址的信息。我一直在使用inet_ntop来实现这一目标,并且通常对大多数域都运行良好。当我在google.com或amazon.com等网站上试用时,相同的IP地址似乎会重复打印。
示例输出: 主持人:google.com IPv4:54.239.17.6 IPv4:54.239.17.6 IPv4:54.239.17.6 IPv4:54.239.17.6 IPv4:54.239.17.6 IPv4:54.239.17.6 ....
我想知道是否有人经历过这种情况,我做错了什么,或者这与网站的配置方式有关。
error = getaddrinfo(domain, "80", &host_info, &host_list);
// if error exists exit gracefully
if(error != 0)
{
print_conn_err(error);
return EXIT_FAILURE;
}
// print the domain string array
printf("Host: %s\n", domain);
// print IP addresses relating to domain name
printf("IP Address(s):\n");
for(result = host_list; result != NULL; result = host_list->ai_next)
{
void * address;
char * ip_version;
// if result is IPv4 address
if(result->ai_family == AF_INET)
{
struct sockaddr_in * ipv4 = (struct sockaddr_in *)result->ai_addr;
address = &(ipv4->sin_addr);
ip_version = "IPv4";
}
else if(result->ai_family == AF_INET6)
{
struct sockaddr_in6 * ipv6 = (struct sockaddr_in6 *)result->ai_addr;
address = &(ipv6->sin6_addr);
ip_version = "IPv6";
}
else
{
printf("%s", "Not a valid IP addresses \n.");
return EXIT_FAILURE;
}
// convert the IP to a string and print it:
inet_ntop(result->ai_family, address, ip_address, sizeof ip_address);
printf(" %s: %s\n", ip_version, ip_address);
}
freeaddrinfo(result);
我想到的一个想法是用先前的IP检查当前的IP并打破循环。这似乎是一个非常糟糕的解决方案。
答案 0 :(得分:3)
您的代码中存在导致此问题的错误。
for(result = host_list; result != NULL; result = host_list->ai_next)
需要
for(result = host_list; result != NULL; result = result->ai_next)
您的freeaddrinfo(result)
也必须更改为freeaddrinfo(host_list)