Hey all,
I have been trying to write my own TCP checksum function. Iv got a description of how the checksum is calculated from here.
http://en.wikipedia.org/wiki/Transmi...cksum_for_IPv4
In short the one complement of each 16-bit word are added up, and then the result of that is the bitwise complemented.
So to sum all the 16-bit words it would be something like this.
Code:
for each word{
sum += ~word;
}
Then that sum is bitwise complemented.
So here is my function so far. I have not been able to get a correct checksum out of though. Iv been tweaking things all day, and not figured out what I am doing wrong.
Code:
unsigned short tcp_sum_calc(unsigned short len_tcp, unsigned short *src_addr, unsigned short *dest_addr, unsigned short *buff)
{
unsigned short prot_tcp = 6;
unsigned short sum;
int i;
sum = 0;
/* Check if the tcp length is even or odd. Add padding if odd. */
if((len_tcp % 2) == 1){
buff[len_tcp] = 0; // Empty space in the ip buffer should be 0 anyway.
len_tcp += 1; // incrase length to make even.
}
/* add the pseudo header */
sum += ~src_addr[0];
sum += ~src_addr[1];
sum += ~dest_addr[0];
sum += ~dest_addr[1];
sum += ~len_tcp;
sum += ~prot_tcp;
/*
* calculate the checksum for the tcp header and payload
* len_tcp represents number of 8-bit bytes,
* we are working with 16-bit words so divide len_tcp by 2.
*/
for(i=0;i<(len_tcp/2);i++){
sum += buff[i];
}
printf("%02x:", (unsigned short)sum);
// keep only the last 16 bits of the 32 bit calculated sum and add the carries
//sum = (sum >> 16) + (sum & 0xFFFF);
//printf("%02x:", (unsigned short)sum);
//sum += (sum >> 16);
//printf("%02x:", (unsigned short)sum);
// Take the bitwise complement of sum
sum = ~sum;
printf("%02x:\n", (unsigned short)sum);
return ((unsigned short) sum);
}
Thank you.