This blog is only to remind myself of what I've learned (from others or by myself) and only for knowledge sharing. External sources will be clearly stated in [Reference] of each article. I hope this blog won't infringe any copyrights and that it can be useful for interested blog readers.

2008年2月20日 星期三

IPv4 header introduction

[IPv4]

Reference

MAC header IP header Data :::

IP header:

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Version IHL TOS Total length
Identification Flags Fragment offset
TTL Protocol Header checksum
Source IP address
Destination IP address
Options and padding :::

!!NOTES:

1) Real_Fragment_Offset = Fragment_Offset x 8

2) Identification and MF_in_Flags, and Fragment_Offset are used to assemble fragmented IP packets.

3) checksum in C code (ps: checksum field has to be set to 0 first)

typedef unsigned short u16;
typedef unsigned char u8;
typedef unsigned long u32;

//!!NOTES:
// before ip checksum is calculated,
// the IP_Header::Checksum should be 0
u16 ip_sum_calc(u16 len_ip_header, u8 buff[])
{
u16 word16;
u32 sum=0;
u16 i;

// make 16 bit words out of every two adjacent 8 bit words in the packet
// and add them up
for (i=0;i<len_ip_header;i=i+2){
word16 =((buff[i]<<8)&0xFF00)+(buff[i+1]&0xFF);
sum = sum + (u32) word16;
}

// take only 16 bits out of the 32 bit sum and add up the carries
while (sum>>16)
sum = (sum & 0xFFFF)+(sum >> 16);

// one's complement the result
sum = ~sum;

return ((u16) sum);
}

沒有留言: