网络编程中什么时候使用ntohs函数?

Jam*_*ing 1 c c++ network-programming winpcap libpcap

我正在使用 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 */
Run Code Online (Sandbox Code Playgroud)

问题是为什么ntohs只有在获取 tcp_hlennot时才使用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;
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 5

由于IP 标头长度字段非常小(只有四位),因此假定它适合一个字节,因此它永远不会有任何字节顺序问题。只有一个字节,因此没有可以使用该ntohs()函数交换的字节。