szczurcio szczurcio - 1 year ago 125
C Question

Why do inet_ntoa and inet_ntop "reverse" the bytes?

This is a rather basic problem with which, to my surprise, I've had a problem today.

It looks to me like inet_pton and inet_ntoa are reversing the bytes of the IP address they're given:

inet_pton(AF_INET, "", &IP);
printf("%08X\n", IP);

This will print
. And well, if we break down the bytes, it's
01.00.A8.C0 =


IP = 0x7F000001;
struct in_addr ia;
ia.S_un.S_addr = IP;

printf("%s\n", inet_ntoa(ia));

gives me

The first thing that comes to mind is endianness, but I've read the MSDN documentation (1 and 2) and the byte order is not mentioned; it seems weird to me that these functions would arbitrarily decide to use one of the notations without the specification clearly stating that.

What is going on?

Answer Source

Endianness is the reason.

The whole point of these functions is not to produce a "readable" integer, but to set a 32-bit quantity that is ready to be shipped out on the wire. IPv4 requires big-endian ordering, so I would wager that if you did printf("%02X\n", ((char *)&IP)[0]));, you'd get C0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download