ntohs 是 C/C++ 网络编程中常见的函数/宏名,表示 “network to host short”:把16 位(short)的端口号等数值从网络字节序(大端序)转换为主机字节序,以便在不同 CPU 架构(大小端不同)上正确解释数据。常用于读取 TCP/UDP 头部中的端口号字段。
(同类还有 ntohl 用于 32 位。)
/ˌɛn tiː oʊ eɪtʃ ˈɛs/
The code uses ntohs to read the port number correctly.
这段代码使用 ntohs 来正确读取端口号。
After receiving a packet, the program converts the 16-bit fields with ntohs before logging them, ensuring the values are correct on both little-endian and big-endian systems.
接收数据包后,程序在记录日志前用 ntohs 转换这些 16 位字段,确保在小端和大端系统上数值都正确。
ntohs 来自缩写 n(network) + to + h(host) + s(short)。它属于 BSD sockets 传统接口的一部分:网络协议规定多字节整数通常使用网络字节序(大端),而主机可能是小端或大端,因此需要显式转换。
ntohs/htons。 ntohs 解析端口号是典型示例。