ntohs和htons区别?

来源:互联网 发布:战神诀披风进阶数据 编辑:程序博客网 时间:2024/05/02 04:49

一直以来都对这个两个函数含含糊糊的,今天又用到所以特意查看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

 从上面的头文件内容可以看出,ntohs和htons是一样的。如果平台是大字序的(如Pocket PC),则这些函数不作任何转换,只有在平台是小字序时(如X86),这些函数才进行相应的转换,htons和ntohs(以及htonl和ntohl)实际上没有任何区别,都是把字节序反转,只在于使用者对网络端和主机端理解意义的不同。

原创粉丝点击