udp_checksum.c
Dear All I have written a client server program for file transmission from one system to other using UDP. Can i use the cksum number in the udp header to validate if the received packet is corrupted or not? If yes, how can i extract the header and validate it. Also is there any way that i can call cksum in c program? Udp.c- // This sample program must be run by root lol! Udp header length: 8 bytes (=64 bits) unsigned int checksum(uint16t.usBuff, int isize) unsigned.
uint16_tudp_checksum(struct udphdr *p_udp_header, size_t len, uint32_t src_addr, uint32_t dest_addr) |
{ |
constuint16_t *buf = (constuint16_t*)p_udp_header; |
uint16_t *ip_src = (void*)&src_addr, *ip_dst = (void*)&dest_addr; |
uint32_t sum; |
size_t length = len; |
// Calculate the sum |
sum = 0; |
while (len > 1) |
{ |
sum += *buf++; |
if (sum & 0x80000000) |
sum = (sum & 0xFFFF) + (sum >> 16); |
len -= 2; |
} |
if (len & 1) |
// Add the padding if the packet lenght is odd |
sum += *((uint8_t*)buf); |
// Add the pseudo-header |
sum += *(ip_src++); |
sum += *ip_src; |
sum += *(ip_dst++); |
sum += *ip_dst; |
sum += htons(IPPROTO_UDP); |
sum += htons(length); |
// Add the carries |
while (sum >> 16) |
sum = (sum & 0xFFFF) + (sum >> 16); |
// Return the one's complement of sum |
return (uint16_t)~sum; |
} |
commented Jan 16, 2019
why if (sum & 0x80000000) ? |
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment
udp_checksum.c
uint16_tudp_checksum(struct udphdr *p_udp_header, size_t len, uint32_t src_addr, uint32_t dest_addr) |
{ |
constuint16_t *buf = (constuint16_t*)p_udp_header; |
uint16_t *ip_src = (void*)&src_addr, *ip_dst = (void*)&dest_addr; |
uint32_t sum; |
size_t length = len; |
// Calculate the sum |
sum = 0; |
while (len > 1) |
{ |
sum += *buf++; |
if (sum & 0x80000000) |
sum = (sum & 0xFFFF) + (sum >> 16); |
len -= 2; |
} |
if (len & 1) |
// Add the padding if the packet lenght is odd |
sum += *((uint8_t*)buf); |
// Add the pseudo-header |
sum += *(ip_src++); |
sum += *ip_src; |
sum += *(ip_dst++); |
sum += *ip_dst; |
sum += htons(IPPROTO_UDP); |
sum += htons(length); |
// Add the carries |
while (sum >> 16) |
sum = (sum & 0xFFFF) + (sum >> 16); |
// Return the one's complement of sum |
return (uint16_t)~sum; |
} |
commented Jan 16, 2019
why if (sum & 0x80000000) ? |
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment