I'm trying to build a tool to gather information about IP addresses based on domain names. I've been using inet_ntop to achieve this and is generally working quite well for most domains. When I try it on sites like google.com or amazon.com the same IP address seems to get printed repeatedly.
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 ....
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. 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)