There is a clear checksum function that correctly handles Endianness tasks in Scapy ( http://www.secdev.org/projects/scapy , GPLv2).
In Python 2.7, scapy utils.py:
if struct.pack("H",1) == "\x00\x01": # big endian def checksum(pkt): if len(pkt) % 2 == 1: pkt += "\0" s = sum(array.array("H", pkt)) s = (s >> 16) + (s & 0xffff) s += s >> 16 s = ~s return s & 0xffff else: def checksum(pkt): if len(pkt) % 2 == 1: pkt += "\0" s = sum(array.array("H", pkt)) s = (s >> 16) + (s & 0xffff) s += s >> 16 s = ~s return (((s>>8)&0xff)|s<<8) & 0xffff
This is correct for any protocol that uses the IP header checksum (IP, TCP, UDP, ICMP). However, UDP also has a special case where a checksum calculated as 0x0000 must be transmitted as 0xffff. The above function does not take this into account, so for UDP you will have to handle this special case.
source share