Why do both `htons` and `ntohs` exist?
Asked Answered
R

2

7

I am not sure why htons and ntohs both exist in the standard library. They do exactly the same thing -- unless I'm confused somehow!

The same goes for htonl and ntohl.

Rhetorical answered 2/6, 2016 at 17:27 Comment(0)
H
8

They make for self-documenting code that tells the reader whether the data is in host- or network- order.

Harryharsh answered 2/6, 2016 at 17:30 Comment(0)
N
7

This is in case a machine has some sort of unusual endianness besides big-endian or little-endian that isn't one or more simple byte swaps.

For example, if the value 0x0A0B0C0D was represented internally as 0B 0C 0D 0A, then passing this representation to htonl would return 0x0A0B0C0D but ntohl would return 0x0C0D0A0B.

I'm not aware of any platforms that have such a representation, but the presence of separate functions for host-to-network and network-to-host allows for the possibility.

Nicosia answered 2/6, 2016 at 17:55 Comment(1)
I was thinking of this case as well, but refrained from writing an answer as asymmetric byte order is something for eccentric chip designers on dope ... ;-)Piecemeal

© 2022 - 2024 — McMap. All rights reserved.