I read the documentation from one of the answers:
The ntohs function takes a 16-bit number in TCP/IP network byte order (the AF_INET or AF_INET6 address family) and returns a 16-bit number in host byte order.
Please explain with an example, as in what is network byte order and what is the host byte order.
The number 1000 is, in binary, 1111101000.
If that's in a 16-bit binary number, that's 0000001111101000.
If that's split into two 8-bit bytes, that's two bytes with the values 00000011 and 11101000.
Those two bytes can be in two different orders:
In a byte-addressible machine, the hardware can be "big-endian" or "little-endian", depending on which byte is stored at a lower address in memory. Most personal computers are little-endian; larger computers come in both big-endian and little-endian flavors, with a number of larger computers (IBM mainframes and midrange computers and SPARC servers, for example) being big-endian.
Most networks are bit-serial, so the bits are transmitted one after the other. The bits of a byte might be transmitted with the most-significant or least-significant bit first, but the network hardware will hide those details from the processor. However, they will transmit bytes in the order they are in the memory of the host, so, if a little-endian machine is transmitting data to a big-endian machine, the number that the little-endian machine transmits would look different on the receiving big-endian machine; those differences are not hidden by the network hardware.
Therefore, in order to allow big-endian and little-endian machines to communicate, at each protocol layer, either:
Various Internet protocols use the first strategy, specifying big-endian as the byte order; it's referred to as "network byte order" in various RFCs. (Microsoft's SMB file access protocol also uses the first strategy, but specifies little-endian.)
So "network byte order" is big-endian. "Host byte order" is the byte order of the machine you're using; it could be big-endian, in which case ntohs()
just returns the value you gave it, or it could be little-endian, in which case ntohs()
swaps the two bytes of the value you gave it and returns that value. For example, on a big-endian machine, ntohs(1000)
would return 1000, and, on a little-endian machine, ntohs(1000)
would swap the high-order and low-order bytes, giving 1110100000000011 in binary or 59395 in decimal.