首页 > 代码库 > IP校验和

IP校验和

  1 #include <stdio.h>  2 #include <unistd.h>  3 #include <linux/if_ether.h>  4 #include <linux/ip.h>  5 #include <linux/udp.h>  6 #include <linux/types.h>  7   8 unsigned short check_sum(unsigned char *data, int len);  9  10 int main() 11 { 12         unsigned char data[1024] = { 13         0x45, 0x00, 14         0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 15         0x00, 0x00, 0xc0, 0xa8, 0x1f, 0x72, 0xc0, 0xa8, 16         0x1f, 0x7a 17         }; 18  19         unsigned short ret = 0; 20         ret = check_sum(data, 20); 21         printf("check sum is %x\n", htons(ret)); 22 } 23  24 unsigned short check_sum(unsigned char *data, int len) 25 { 26         unsigned short ret = 0; 27         int i = 0; 28         int sum = 0; 29         unsigned short *p = (short *)data; 30         for(i=0; i<len/2; i++) 31                 sum = sum + ntohs(p[i]); 32         if(sum > 0xffff){ 33                 sum = (sum & 0x0ffff) + ((sum & 0xf0000) >> 16); 34         } 35  36         ret = (short)sum; 37         return ~ret; 38 }
  1. 0x00 0x00
  2. 按两字节相加完回滚(如果结果是2856D,则2要按0002 继续加 856D)
  3. htons()

IP校验和