Network Byte Order

 < Day Day Up > 



A given computer architecture defines the format by which data is stored within the computer’s memory. Two formats exist, which are opposites of one another. The first format, known as little endian, stores the contiguous bytes of a type in memory with the least significant byte (0x04) first and the most significant byte last (0x01). The big endian format stores contiguous bytes in the opposite order; the most significant byte is stored first and the least significant byte is stored last. See Figure 2.2 for a graphical description.

click to expand
Figure 2.2: Memory storage of little and big endian formats.

Although the data contained in the messages uses a format predefined by the applications that use it, the values stored in the packet headers are in big endian format. This means that processors that utilize big endian (such as Motorola® processors) require no byte-swapping to occur. Processors that utilize little endian (such as Intel® processors) require all packet fields of more than one byte to be swapped from little endian to big endian. It’s a slight advantage, therefore, for a network processor to use the byte ordering of the network (what’s called network byte order, or NBO). The lack of byte swapping to convert from host byte order to network byte order can lead to a slight performance advantage.

Note 

The original concept of endianness comes from Jonathan Swift’s Gulliver’s Travels. In this book, the nations of Liliput and Blefuscu waged war against each another over which end one should cut open a boiled egg—the big end or the little end.

Swapping Byte Order

The Sockets API provides four functions to swap the byte order of fundamental types. These functions are ntohs (network-to-host-short), htons (host-to-network-short), ntohl (network-to-host-long), and htonl (host-to-network-long). These four functions operate on two basic types, shorts (16-bit words) and longs (32-bit words). A function is provided for both converting to network byte order (from host byte order) and converting to host byte order (from network byte order).

It’s common practice to use these functions, even if the host architecture uses network byte order (big endian). This permits the software to be easily ported to host architectures that use little endian byte ordering.



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net