Reputation: 2621
I followed this question and answer to convert an IP address (number and dot notation) to its respective unsigned integer equivalent. In otherwords, I make use of the inet_aton function
I made a very quick program in c to test out the function. The following is the code:
int main(int argc, char** argv) {
char* ip1 = "125.113.200.068";
char* ip2 = "125.113.200.068";
struct in_addr ip1s;
inet_aton(ip1, &ip1s);
struct in_addr ip2s;
inet_aton(ip2, &ip2s);
if (ip1s.s_addr == ip2s.s_addr) {
printf("equal: %u = %u", ip1s.s_addr, ip2s.s_addr);
}else{
printf("not equal: %u != %u", ip1s.s_addr, ip2s.s_addr);
}
return (EXIT_SUCCESS);
}
Despite the fact that the two strings where given the same ip, I get the following as output:
not equal: 15774463 != 0
Furthermore, if I remove the 0 such that the ips are set to 125.113.200.68, then the function returns two equal unsigned integers. Do preceding 0s make an IP invalid? But if it is the case, why did I get a non zero value for one of the ips in the former example?
Upvotes: 2
Views: 325
Reputation: 179412
You have to check inet_aton
's return value:
inet_aton()
returns non-zero if the address is a valid one, and it returns zero if the address is invalid.
Your addresses are invalid. 068
is interpreted as octal because of the leading zero, and 8
is not a valid octal digit. If inet_aton
fails, it doesn't change the in_addr
structures, so what you're printing out is random stack garbage.
In any case, inet_aton
is not recommended for new code. Use inet_pton
instead.
Upvotes: 3