Reputation: 13
I wanted to know what byte sorting method my PC uses. So I experimented to see if any u_long variable remains the same after it is converted to the htons() function.
u_long example = 0x12345678;
printf("#%x -> #%x -> #%x\n", example, htonl(example), htonl(htonl(example)));
During the test, I called the htons function once more, and once again, I found that the htons applied function changed the value again.
Output
#12345678 -> #78563412 -> #12345678
Expected
#12345678 -> #78563412 -> #78563412
The htons function sorts all the data into big endian, Why does the data change when called again? What's the problem? Please let me know my mistake.
Upvotes: 0
Views: 649
Reputation: 41281
htonl
takes a long, expecting host byte order, and converts it to network byte order. On a host where the host byte order is opposite the network byte order, it swaps the bytes. Calling it again will just swap the bytes again. There's no sorting involved, just swapping.
When you call htonl
with a parameter of htonl(0x12345678)
, it has no way of knowing that this sequence of four bytes means 0x12345678 in network byte order. For all it knows, the input could literally be the integer 0x78563412 expressed in host byte order. It simply does the swap as designed and documented, expecting its input in host order and emitting an output in network byte order.
If you subvert its documented expectations, you are not guaranteed a meaningful result, just like if you e.g. passed a pointer to free
that did not come from malloc
.
Upvotes: 4