2

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?

Community
  • 1
  • 1
Goaler444
  • 2,591
  • 6
  • 35
  • 53

1 Answers1

3

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • That said, if you're going to pass `AF_INET` as the address family then the difference between `inet_aton` and `inet_pton` is negligible. The advice really amounts to, "write your applications to support IPv6". Just using `inet_pton` in place of `inet_aton` would be kind of missing the point :-) – Steve Jessop Apr 03 '13 at 23:43
  • IIRC `inet_aton` is also not perfectly portable. It works on most systems with BSD networking, but doesn't exist on some systems like Windows (under Winsock2). – nneonneo Apr 03 '13 at 23:54