Created
October 9, 2011 14:40
-
-
Save GreenRecycleBin/1273763 to your computer and use it in GitHub Desktop.
UDP checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uint16_t udp_checksum(struct udphdr *p_udp_header, size_t len, uint32_t src_addr, uint32_t dest_addr) | |
{ | |
const uint16_t *buf = (const uint16_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; | |
} |
you may call it like
struct udphdr *udp_hdr = ...;
udp_hdr->uh_sum = 0;
udp_hdr->uh_sum = udp_checksum(udp_hdr, swap_uint16(udp_hdr->uh_ulen), ip_header->ip_src.s_addr, ip_header->ip_dst.s_addr);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why
if (sum & 0x80000000)
?