#include <stdio.h>
#include <unistd.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/types.h> unsigned short check_sum(unsigned char *data, int len); int main()
{
unsigned char data[] = {
0x45, 0x00,
0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11,
0x00, 0x00, 0xc0, 0xa8, 0x1f, 0x72, 0xc0, 0xa8,
0x1f, 0x7a
}; unsigned short ret = ;
ret = check_sum(data, );
printf("check sum is %x\n", htons(ret));
} unsigned short check_sum(unsigned char *data, int len)
{
unsigned short ret = ;
int i = ;
int sum = ;
unsigned short *p = (short *)data;
for(i=; i<len/; i++)
sum = sum + ntohs(p[i]);
if(sum > 0xffff){
sum = (sum & 0x0ffff) + ((sum & 0xf0000) >> );
} ret = (short)sum;
return ~ret;
}
- 0x00 0x00
- 按两字节相加完回滚(如果结果是2856D,则2要按0002 继续加 856D)
- ~
- htons()