一直以来都对这个两个函数含含糊糊的,今天又用到所以特意查看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)实际上没有任何区别,都是把字节序反转,只在于使用者对网络端和主机端理解意义的不同。

GitHub 加速计划 / li / linux-dash
13
2
下载
A beautiful web dashboard for Linux
最近提交(Master分支:3 个月前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐