Skip to content

Instantly share code, notes, and snippets.

@gangliao
Last active July 1, 2018 04:20
Show Gist options
  • Save gangliao/6f0bcb3a377f941d7a517eb4b9b3af44 to your computer and use it in GitHub Desktop.
Save gangliao/6f0bcb3a377f941d7a517eb4b9b3af44 to your computer and use it in GitHub Desktop.
checksum
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
/*
IP Checksum
Benefits: fast, easy to compute and check which is motivated by earliest
software implementation.
Drawbacks: poor error detection
1. Only guarantees detecting a single bit error;
2. Can detect other errors, but actual guarantees are both weak and complex.
*/
typedef struct
{
int srcIp;
int dstIp;
unsigned 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()
{
unsigned 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((unsigned short *)&udphdr, 22);
printf("[test ...] b = Ox%04x\n", b & 0xffff);
b = check_sum((unsigned short *)arr, 22);
printf("[test arr] b = Ox%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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment