何时在网络编程中使用 ntohs 函数

When to use ntohs function in net programming?

本文关键字:ntohs 函数 网络编程 何时      更新时间:2023-10-16

我正在使用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(阅读短值的净到主机转换)。原因是在将这些数字编码为多字节时,不同系统的字节序。