Unix Network Programming Manual
Prev Page Next Page

Network Byte Order

One of the more nagging problems in network communications is that different machines organize their data differently in memory. When you store a four{--}byte integer in memory, you can store the individual bytes with the most significant byte in the lowest byte address in memory or in the highest byte. If you write the value 185.16.123.45 (using the nifty Internet descriptor for a four{--}byte integer) at location 1000. You could store 185 at 1000 and 45 at 1003, or you could store 185 at 1003 and 45 at 1000. The first scheme is known as Big Endian, because the most significant part of the number is in low memory, and the second is known as Little Endian. Without getting into the politics of which is better, suffice it to say that Digital Equipment Corporation and Intel use the Little Endian scheme, and virtually everyone else uses Big Endian.

The problem is this. If an integer is sent from a machine with one type of storage to a machine with another type, the bytes will be stored in the wrong order, and hence they will be interpreted as a value incorrectly. To avoid this, the Internet specifies what is called network byte order - a specified order for any integer that is sent over the network. It doesn't really matter, but the chosen method is Big Endian. If you choose to ignore this problem, you may not have any problems, but when they do occur, they are difficult to find, so it is best to always assume the worst.

If you send an integer, you should to convert it to network byte order using htons, htonl for two and four-byte integers respectively. When you receive an integer, you have to convert it from network byte order using ntohs and ntohl for network to two or four-byte integers, respectively. Note that bytes do not need to be reordered, because all machines handle bytes the same. However, floating point values are even worse, because there are many ways of handling the mantissa and characteristic portions of floats.

In Client1, htons is used to convert the integer number of the port to network byte order, because that is the expected order for the structure. Another example is the following code that prepares a two shorts and a long integer for transmission.


Prev Page Next Page