何时在网络编程中使用 ntohs 函数
When to use ntohs function in net programming?
我正在使用WinPcap学习网络编程。这是片段:
int ip_hlen = (ih->ver_ihl & 0xf) * 4; /* get ip header length */
tcp_header *th = (tcp_header *) ((u_char*)ih + ip_len);
int tcp_hlen = (ntohs(th->th_len_resv_code) & 0xf000) >> 12)*4; /* get tcp header length */
问题是为什么ntohs
只在获得tcp_hlen
而不是ip_hlen
时使用。
事实上,ntohs
只接受u_short
参数解释一点。http://msdn.microsoft.com/en-us/library/windows/desktop/ms740075%28v=vs.85%29.aspx
我仍然对何时使用ntohs感到困惑。
以下是 IP 和 TCP 数据包定义的结构:
/* ipv4 header */
typedef struct ip_header {
u_char ver_ihl; /* version and ip header length */
u_char tos; /* type of service */
u_short tlen; /* total length */
u_short identification; /* identification */
u_short flags_fo; // flags and fragment offset
u_char ttl; /* time to live */
u_char proto; /* protocol */
u_short crc; /* header checksum */
ip_address saddr; /* source address */
ip_address daddr; /* destination address */
u_int op_pad; /* option and padding */
}ip_header;
/* tcp header */
typedef struct tcp_header {
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
u_int th_seq; /* sequence number */
u_int th_ack; /* acknowledgement number */
u_short th_len_resv_code; /* datagram length and reserved code */
u_short th_window; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
}tcp_header;
由于 IP 标头长度字段非常小(只有四位),因此假定它适合一个字节,因此它永远不会有任何字节序问题。只有一个字节,因此没有字节可以使用ntohs()
函数交换。
如果你的值是8bit长,则不用担心字节序。仅此而已。不能对一个字节中的字节重新排序。
ntohs
是网络到主机 - 短。短是 16 位。使用 ntohs 的一个示例是 16 位"端口"值,如果您从 sockaddr 结构中提取端口值。
uint16_t portNo = ntohs(sock.sin_port);
你应该做转换,htons,当OYU首先将端口号放入Sockaddr结构中时。
您只需要在期望进行恩迪亚内斯转换的地方使用它。特别是标头和协议变量的一部分。对于数据包的用户部分(您的数据),由您自行决定。
这很简单。每当通过网络接收时遇到 16 位值时,您都需要ntohs
(阅读短值的净到主机转换)。原因是在将这些数字编码为多字节时,不同系统的字节序。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 何时在网络编程中使用 ntohs 函数