htons()
converts host byte order to network byte order.
Network byte order is Big-Endian and host byte order can be either Little-Endian or Big-Endian.
On a Little Endian system htons()
will convert the order of a multi-byte variable to Big-Endian. What will htons()
do in case if the host byte order is also Big-Endian?
The htons() function translates a short integer from host byte order to network byte order. Parameter Description a. The unsigned short integer to be put into network byte order. in_port_t hostshort. Is typed to the unsigned short integer to be put into network byte order.
htons(), htonl(), ntohs(), ntohl() Since Intel is a "little-endian" machine, it's far more politically correct to call our preferred byte ordering "Network Byte Order". So these functions convert from your native byte order to network byte order and back again.
Byte Ordering Functionsunsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order. unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order.
Function description: The function htonl converts an integer number from the byte order accepted on the computer into the network byte order. The function htons converts an integer short number from the byte order accepted on the computer into the network byte order.
What will
htons()
do in case if the host byte order is also big endian?
Nothing - quite literally. The purpose of introducing htons()
in the first place is to let you write code that does not care about the endianness of your system. Header file where the functions are defined is the only place where endianness comes into play.
Here is one implementation that replaces htons
with parentheses around its parameter expression:
#if BYTE_ORDER == BIG_ENDIAN
#define HTONS(n) (n)
#define NTOHS(n) (n)
#define HTONL(n) (n)
#define NTOHL(n) (n)
#else
#define HTONS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define NTOHS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
((((unsigned long)(n) & 0xFF00)) << 8) | \
((((unsigned long)(n) & 0xFF0000)) >> 8) | \
((((unsigned long)(n) & 0xFF000000)) >> 24))
#define NTOHL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
((((unsigned long)(n) & 0xFF00)) << 8) | \
((((unsigned long)(n) & 0xFF0000)) >> 8) | \
((((unsigned long)(n) & 0xFF000000)) >> 24))
#endif
#define htons(n) HTONS(n)
#define ntohs(n) NTOHS(n)
#define htonl(n) HTONL(n)
#define ntohl(n) NTOHL(n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With