Determining the size of the IP header. Why is this different from others?

Take a look at this code segment:

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)); } 

What confuses me is in the case of determining the size of the other headers that we usually do, sizeof(struct tcphdr) or sizeof(struct ethhdr) , but for the size of the IP header, we do not do sizeof, but do ip_header->ihl*4 . Why is this so? And what is this 4?

Here's how to declare an IP heder structure:

 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 }; 
+4
source share
1 answer

This is a problem of different units. The IHL field in the IP header is defined as follows:

The length of the Internet header is the length of the Internet header of 32 bits of the word .

And this size is not fixed (due to valid but discouraged IP parameters). Thus, one packet may have IHL = 5, the next may have IHL = 6, etc.

+5
source

Source: https://habr.com/ru/post/1391826/


All Articles