Of course, you could make the pointers private and pass them in the function call. They must point to the winpcap entities that contain a header and a packet, respectively, before the call to UDPchecksum(). In my version these pointers were members of a class, but I removed that detail for this example. Winpcap fills a structure with the winpcap header information along with a buffer containing the captured packet. To use the UDPchecksum() routine you can simply paste it into your winpcap project (or any project that has a packet capture tool) and rename the global pointers to match the names you choose. Thus, you save a little overhead by not calling ntohs() for each grouping of bytes.įinally, zeroes don't affect the checksum result, so padding a leftover byte with zeroes to form a long integer is ok. If you are only checking the checksum at the receiving end, the result should be 0xFFFF, so in this case the byte order doesn't matter at all. Second, the byte order doesn't matter until the end if you are generating a checksum to insert into a packet. At the end of the process you can fold the 64 bits into 16 bits to get a valid checksum result.
#Udp checksum calculator 32 bit#
For 32 bit groupings, the accumulator needs to be 64 bits. In C it is not easy to check for integer overflow, so you need an accumulator that can hold all of the overflows from all the summing. However, in RFC 1071 I found three key principles that allow for a more efficient process:įirst, the size of the groupings doesn't matter if you fold the result back into a 16 bit word at the end. I use winpcap () to monitor a UDP data stream and I needed a checksum routine, but all the examples I found were based on inefficient 16-bit groupings of the bytes.
See RFC 1071 for a discourse on the theory of the internet checksum. In particular, you need to understand the pseudo header used for the UDP checksum. See RFC 768 to read about the UDP protocol and the UDP checksum. This article presents a checksum routine for UPD/IP packets using 32-bit groupings.