Why do inet_ntoa and inet_ntop "reverse" the bytes?
Asked Answered
F

2

4

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?

Forevermore answered 10/5, 2015 at 16:44 Comment(1)
It's unfortunate that the documentation for the in_addr structure doesn't explicitly point out that the address is big-endian. The documentation for inet_pton does, though.Musgrove
S
10

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.

Senzer answered 10/5, 2015 at 16:48 Comment(4)
I'd recommend some additional reading why x86 uses little endian although it may be a bit confusing for humans at first.Trickster
@Vyktor: Makes sense for what? IPv4 is big-endian, so there's no question of using little-endian!Senzer
Okay, so basically, when I give my data to one of these functions, they'll convert it to a format appropriate for the low-level networking land, and whoever I'm exchanging information with will do the opposite on the other end, correct?Forevermore
Hello @OliverCharlesworth! your reply helped me a lot but I'd like to know if I understand correctly... When we put printf("%02X\n", ((char *)&IP)[0])); is it mean we are getting the Most Significant Byte from the memory?Tachymetry
E
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.

Expunge answered 10/5, 2015 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.