Ignoring Endianness of Parameters in API Functions

 < Day Day Up > 



A common mistake in Sockets applications is not taking into account the parameters that must be presented in network byte order (particularly on hosts that utilize little-endian byte ordering). Recall that non-byte data on the Internet is in what is called network byte order, specifically big endian. On architectures that are little endian, such as Intel processors, bytes must be swapped in order to maintain consistency of control data (such as packet headers). For this reason, the byte ordering functions ntohs, htons, ntohl, and htonl exist to provide the swapping capability. All network programs should use these, even if they’re currently running on a big-endian architecture because porting them to run on little-endian architectures will then be much simpler. It should be noted that byte-swapping functions are NULL functions on architectures that are already big-endian.

One of the most common errors that can be found in network applications comes in defining a socket address, such as:

struct sockaddr_in saddr; memset( &saddr, 0, sizeof(saddr) ); saddr.sin_family = AF_INET; saddr.sin_port = 80; saddr.sin_addr.s_addr = inet_addr( "192.168.1.1" );

At first glance, this socket address appears to specify the interface identified by IP address “192.168.1.1” and port 80. The problem is that the sin_port (and sin_addr) must be in network byte order. On a little-endian architecture, the port bound here is actually 20480 (due to improper byte ordering). This bug is easily fixed by using the htons function (host-to-network-short).

struct sockaddr_in saddr; memset( &saddr, 0, sizeof(saddr) ); saddr.sin_family = AF_INET; saddr.sin_port = htons(80); saddr.sin_addr.s_addr = inet_addr( "192.168.1.1" );

Note that the inet_* functions (inet_addr, inet_ntoa, inet_aton) automatically perform the byte swapping internally and, therefore, their result is in the proper order. Although this discussion is true for the C language, it may not actually apply to other languages discussed in this text.



 < 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