【发布时间】:2012-02-14 02:27:01
【问题描述】:
看看这段代码:
if(ip_header->protocol == IPPROTO_TCP)
{
tcp_header = (struct tcphdr*)(packet + sizeof(struct ethhdr) + ip_header->ihl*4);
/* Print the Dest and Src ports */
printf("Source Port: %d\n", ntohs(tcp_header->source));
printf("Dest Port: %d\n", ntohs(tcp_header->dest));
}
我感到困惑的是,在确定我们通常执行的其他标头的大小时,sizeof(struct tcphdr) 或 sizeof(struct ethhdr) 但对于 IP 标头大小,我们不执行 sizeof,而是执行 ip_header->ihl*4。为什么会这样?还有这个 4 是干什么用的?
IP heder的struct声明如下:
00116 struct iphdr {
00117 #if defined(__LITTLE_ENDIAN_BITFIELD)
00118 __u8 ihl:4,
00119 version:4;
00120 #elif defined (__BIG_ENDIAN_BITFIELD)
00121 __u8 version:4,
00122 ihl:4;
00123 #else
00124 #error "Please fix <asm/byteorder.h>"
00125 #endif
00126 __u8 tos;
00127 __u16 tot_len;
00128 __u16 id;
00129 __u16 frag_off;
00130 __u8 ttl;
00131 __u8 protocol;
00132 __u16 check;
00133 __u32 saddr;
00134 __u32 daddr;
00135 /*The options start here. */
00136 };
【问题讨论】:
标签: linux header network-programming ip ipv4