由linux的源代码(/include/netinet/in.h)可以看到:
# if __BYTE_ORDER == __BIG_ENDIAN
/* The host byte order is the same as network byte order,
so these functions are all just identity. */
# define ntohl(x) (x)
# define ntohs(x) (x)
# define htonl(x) (x)
# define htons(x) (x)
# else
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define ntohl(x) __bswap_32 (x)
# define ntohs(x) __bswap_16 (x)
# define htonl(x) __bswap_32 (x)
# define htons(x) __bswap_16 (x)
# endif
# endif
结论:
由头文件中定义的宏可以看到,htons和ntohs完全等价。
当主机是大端序时,使用htons或ntohs后仍等于原值。
当主机是小端序时,使用hton或ntohs使原值的字节序翻转。