Why do inet_ntoa and inet_ntop “reverse” the bytes?

£可爱£侵袭症+ 提交于 2019-12-04 18:37:00

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!