Search code examples
cnetwork-programmingwinsockendianness

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:

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

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

Similarly:

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

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

gives me 1.0.0.127.

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?


Solution

  • 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.