Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Different system architectures use different byte ordering, either little endian (least significant byte first) or big endian (most significant byte first). IA-32 is an example of an architecture that implements little endian byte ordering. In contrast, PowerPC and most Network Protocols (including TCP and IP) use big endian.

When transferring data between systems of different endianness, the programmer must take care to reverse the byte ordering before they interpret the data.

The functions htonl(), htons(), ntohl(), and ntohs() can be used to transfer between network byte ordering (big endian) and the host's byte ordering. These On big endian systems, these functions do nothing on big endian systems.

...

. They may also be implemented as macros rather than functions.

Non-Compliant Code Example

In this noncompliant code example, the programmer tries to read an unsigned 32-bit integer off a previously connected network socket.

...

This program prints out the number received off from the socket using an incorrect byte ordering. For example, if the value 4 is sent from a big endian machine, and the sending and receiving systems have opposite byte orderingreceiving system is little endian, the value 536,870,912 is read. This problem can be corrected by sending and receiving using network byte ordering.

...

Code Block
bgColor#ccccff
/* sock is a connected TCP socket */

uint32_t num;

if (recv(sock, (void *)&num, sizeof(uint32_t), 0) < 0) {
  /*handle Handle error */
}

num = ntohl(num);
printf("We recieved %u from the network!\n", (unsigned int)num);

...

The reciprocal function htonl() (host to network long) should be used before sending any data to another system over network protocols.Notes

Portability Details:

  • ntohs(), ntohl(), htons(), and htonl() are not part of the C standard, and are consequently not guaranteed to be portable to non-POSIX systems.
  • The POSIX implementations of ntohs(), ntohl(), htons() and htonl() take arguments of types uint16_t and uint32_t and can be found in the header file <arpa/inet.h>.
  • The Windows implementations use unsigned short and unsigned long and can be found in the header file <winsock2.h>.
  • Other variants of ntoht() and htont() may exist on some systems, such as ntohi()/htoni() or ntohll()/htonll().

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

POS39-C

medium

high likely

low

P3

L3

References

Wiki Markup
\[[Open Group 04|AA. C References#Open Group 04]\] [htonl, htons, ntohl, ntohs - convert values between host and network byte order|http://www.opengroup.org/onlinepubs/009695399/functions/htonl.html]
POSIX ntohl man page