ntohs 与 ntohl
🔢 网络字节序 → 主机字节序的转换函数。
C 原型
c
#include <arpa/inet.h>
uint16_t ntohs(uint16_t netshort); // network to host short (16位)
uint32_t ntohl(uint32_t netlong); // network to host long (32位)| 函数 | 转换 | 用途 |
|---|---|---|
ntohs | 16 位 网络序→主机序 | 端口 |
ntohl | 32 位 网络序→主机序 | IP 地址 |
r0capture 的用法
javascript
// initializeGlobals 包装
ntohs = new NativeFunction(addresses["ntohs"], "uint16", ["uint16"]);
ntohl = new NativeFunction(addresses["ntohl"], "uint32", ["uint32"]);
// getPortsAndAddresses 里用 ntohl 转 IP
message[src_dst[i] + "_addr"] = ntohl(ipToNumber(sockAddr.ip.split(":").pop()));IP 地址流转
为什么 ipToNumber 小端拼接后再 ntohl?因为最终要存的是大端 uint32(网络序),Python 端用 struct.pack(">I") 还原。详见 ipToNumber。
为什么不直接大端拼接
可以,但代码用「小端拼接 + ntohl」更对称(端口也走 ntohs)。且 ntohl 是 libc 现成函数,调用方便。
端口
javascript
message[src_dst[i] + "_port"] = (sockAddr.port & 0xFFFF)端口直接用 & 0xFFFF 取低 16 位,未走 ntohs(sockAddr.port 已是主机序整数)。