What does htons() do on a Big-Endian system?
Asked Answered
F

1

7

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?

Farther answered 28/3, 2016 at 12:13 Comment(1)
It is a noop - does nothingSensual
F
14

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)
Fleck answered 28/3, 2016 at 12:16 Comment(1)
Is the endian of a "network order" defined to be "big endian" or is that network dependent? I suspect it once was network dependent, but Linux now only considers TCP/IP network byte order - which is big-endian.Thermophone

© 2022 - 2024 — McMap. All rights reserved.