[英]inet_ntop repeatedly looping IP
I'm trying to build a tool to gather information about IP addresses based on domain names. 我正在尝试构建一个工具来基于域名收集有关IP地址的信息。 I've been using inet_ntop to achieve this and is generally working quite well for most domains. 我一直在使用inet_ntop来实现这一点,并且在大多数域中通常都运行良好。 When I try it on sites like google.com or amazon.com the same IP address seems to get printed repeatedly. 当我在google.com或amazon.com等网站上尝试使用该IP地址时,似乎会反复打印该IP地址。
Example Output: Host: 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 .... 输出示例:主机: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 ....
I was wondering if anyone has experienced this, am I doing something wrong or is this something to do with how the sites are configured. 我想知道是否有人遇到过这种情况,是我做错了事还是与网站的配置有关?
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);
One idea I thought of was to check the current IP with the previous IP and break the loop. 我想到的一个想法是用先前的IP检查当前IP并中断循环。 This seems like quite a hacky solution though. 不过,这似乎是一个很棘手的解决方案。
There's a bug in your code causing this. 您的代码中有一个错误导致此错误。
for(result = host_list; result != NULL; result = host_list->ai_next)
needs to be 需要是
for(result = host_list; result != NULL; result = result->ai_next)
Your freeaddrinfo(result)
also must be changed to freeaddrinfo(host_list)
您的freeaddrinfo(result)
也必须更改为freeaddrinfo(host_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.