Hi,
I'm taking a networking class and my current project is to implement a "reliable data transfer protocol". So we're given a checksum function to both create a checksum for our packets and to check if the packets are error free. My problem is everytime I tried to check, I get a result that says packet has errors.
Here's the function:
What I did is: I create a packet (a structure), memset it to 0, add in data/headers, feed the struct into this function and get back a checksum to put in the same packet. I sent the packet to the receiving host. At that end I first save the packet checksum into a temp variable, set the checksum in the packet struct to 0, feed it back in the function and what it returns should be the same as the saved checksum I got from the packet itself. But everytime I do that the results don't match. (btw the checksum field is 16 bits)Code:uint16_t checksum(uint16_t *buf, int nwords)
{
uint32_t sum;
for (sum = 0; nwords > 0; nwords--)
sum += *buf++;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return ~sum;
}
So roughly:
on sender side:
on receiver side:Code:Packet p;
memset(&p sizeof(Packet), 0); .
//set contents;
p.checksum = checksum((uint16_t *)&p, sizeof(Packet)/2);
From what I see, this checksum function adds up 16 bit words of the packet, add the sum to its upper 16 bit value and the lower 16 bit value, then add that to the upper 16 bit again and returns the complement. I'm still confused as to how this will give me a unique checksum. But my priority right now is to get this to work / use it correctly.Code:uint16_t check = p.checksum;
p.checksum = 0;
if (checksum((uint16_t *)&p, sizeof(Packet)/2) != check)
//corrupted
If anyone can help/comment I'll greatly appreciate it, Thanks!