首页 > 代码库 > 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 }
- 0x00 0x00
- 按两字节相加完回滚(如果结果是2856D,则2要按0002 继续加 856D)
- ~
- htons()
IP校验和
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。