...
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 functions do nothing on big endian systems.
Noncompliant 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 the socket using an incorrect byte ordering. For example, if the value 4 is sent and the sending and receiving systems have opposite byte ordering, the value 536,870,912 is read. This problem can be corrected by sending and receiving using network byte ordering.
Compliant Code Example
In this compliant code example, the programmer uses the ntohl() function to convert the integer from network byte order to host byte ordering.
...
ntohs(),ntohl(),htons(), andhtonl()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()andhtonl()take arguments of typesuint16_tanduint32_tand can be found in the header file<arpa/inet.h>. - The Windows implementations use
unsigned shortandunsigned longand can be found in the header file<winsock2.h>. - Other variants of
ntoht()andhtont()may exist on some systems, such asntohi()/htoni()orntohll()/htonll().
Risk Assessment
If the programmer is careless then this bug is likely. However it will immediately break the program by printing the incorrect result and therefore should be caught by the programmer during the early stages of debugging and testing. Recognizing a value as in reversed byte ordering, however, can be difficult depending on the type and magnitude of the data.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
POS39-C | medium | high | low | P3 | L3 |