It has to do with the order in which bytes are stored in memory. The decimal number 5001
is 0x1389
in hexadecimal, so the bytes involved are 0x13
and 0x89
. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001
will be stored as
0x89 0x13
The htons()
function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order
0x13 0x89
On a little-endian machine, the number with the swapped bytes is 0x8913
in hexadecimal, which is 35091
in decimal notation. Note that if you were working on a big-endian machine, the htons()
function would not need to do any swapping since the number would already be stored in the right way in memory.
The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.