C++ 网络编程中何时使用ntohs函数?
我正在学习使用WinPcap进行网络编程。以下是片段:C++ 网络编程中何时使用ntohs函数?,c++,c,network-programming,libpcap,winpcap,C++,C,Network Programming,Libpcap,Winpcap,我正在学习使用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 heade
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\u-hlen
而不是ip\u-hlen
时使用
事实上,ntohs
仅将u_short
作为参数进行解释
我仍然对何时使用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;
因为是如此之小(只有四位),它被认为适合一个字节,因此它永远不会有任何端性问题。只有一个字节,因此使用ntohs()
函数没有可交换的字节。因为字节太小(只有四位),所以假定它适合一个字节,因此它永远不会有任何端号问题。只有一个字节,因此使用ntohs()
函数没有可交换的字节。如果您的值为8比特长,则不必担心字节的长度。仅此而已。您不能在一个字节中重新排序字节。如果您的值是8位长,则不必担心字节的尾数。仅此而已。不能在一个字节中对字节重新排序。ntohs
是网络到主机-短。短码是16位。如果要从sockaddr结构中提取端口值,则使用ntohs的示例是16位“port”值
uint16_t portNo = ntohs(sock.sin_port);
当您首先将端口号放入sockaddr结构中时,您应该执行converce,htons
您只需要在需要endianess转换的地方使用它。特别是标头和协议变量的部分。对于数据包(数据)的用户部分,由您自行决定。ntohs
是网络到主机-短。短码是16位。如果要从sockaddr结构中提取端口值,则使用ntohs的示例是16位“port”值
uint16_t portNo = ntohs(sock.sin_port);
当您首先将端口号放入sockaddr结构中时,您应该执行converce,htons
您只需要在需要endianess转换的地方使用它。特别是标头和协议变量的部分。对于数据包的用户部分(您的数据),由您自行决定。这非常简单。每当您在通过网络接收的数据中遇到16位值时,您将需要ntohs
(读取网络到主机的短值转换)。原因是将这些数字编码为多字节时,不同系统的长度不同。这很简单。每当您在通过网络接收的数据中遇到16位值时,您将需要ntohs
(读取网络到主机的短值转换)。原因是将这些数字编码为多字节时,不同系统的长度不同。v1说“短的是16字节”。我想我明天早上会后悔的。v1说“短16字节”。我想明天早上我会后悔的。