Why do inet_ntoa and inet_ntop “reverse” the bytes

2020-07-24 15:47发布

问题:

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?

回答1:

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.



回答2:

Quantities larger than a byte in size (shorts, integers, etc), must leave the wire in Network-byte-order as the Internet standard requires, which by default is Big-endian.

So these functions, like inet_pton, inet_ntoa, htons, htonl and other similar are responsible for swapping the bytes in these quantities depending the endianess of the host. On the other side, the receiver should use corresponding functions to convert network-byte-order to the proper byte order.