#include <stdio.h>
#include <unistd.h>
typedef struct {
int srcIp;
int dstIp;
short udp_len;
char rsv;
char protocol;
unsigned short src_port;
unsigned short dst_port;
unsigned short len;
unsigned short check_sum;
char data[2];
} UDPHDR;
char arr[100] = {0xc0, 0xa8, 0xd1, 0x80, 0xc0, 0xa8, 0xd1, 0x01, 0x00, 0x0a, 0x00, 0x11, 0x13, 0x88, 0x13, 0x88, 0x00, 0x0a, 0x00, 0x00, 0x61, 0x66};
unsigned short check_sum(unsigned short *a, int len);
int main()
{
short b = 0;
UDPHDR udphdr = {0};
udphdr.srcIp = inet_addr("192.168.209.128");
udphdr.dstIp = inet_addr("192.168.209.1");
udphdr.udp_len = htons(10);
udphdr.protocol = 0x11;
udphdr.rsv = 0;
udphdr.src_port = htons(5000);
udphdr.dst_port = htons(5000);
udphdr.len = htons(10);
udphdr.check_sum = 0;
udphdr.data[0] = 0x61;
udphdr.data[1] = 0x66;
b = check_sum((short *)&udphdr, 22);
printf("[test ...] b = %04x\n", b & 0xffff);
b = check_sum((short *)arr, 22);
printf("[test arr] b = %04x\n", b & 0xffff);
return 0;
}
unsigned short check_sum(unsigned short *a, int len)
{
unsigned int sum = 0;
while (len > 1) {
sum += *a++;
len -= 2;
}
if (len) {
sum += *(unsigned char *)a;
}
while (sum >> 16) {
sum = (sum >> 16) + (sum & 0xffff);
}
return (unsigned short)(~sum);
}