Introduction
I happened to come upon a situation where I needed a python implementation of the standard IP header checksum algorithm. I couldn't find a solid python implementation
so I went ahead and wrote my own. I'm hoping this will help someone else out who needs a quick copy and paste implementation.
Background
If you want the full background on how checksumming in IP works check
this out: Description and Example of IP Checksum.
Using the code
To use the code simply pass a list in to ip_header and the size of that list as size. Warning: Don't forget that before you pass your header to the checksum
algorithm you need to ZERO out the checksum field! If you don't, your results will be off. In this case they were the bytes at header[10] and header[11]. Example:
import checksum
header = {}
header[0] = 0x45
header[1] = 0x00
header[2] = 0x00
header[3] = 0xe8
header[4] = 0x00
header[5] = 0x00
header[6] = 0x40
header[7] = 0x00
header[8] = 0x40
header[9] = 0x11
header[10] = 0x0
header[11] = 0x0
header[12] = 0x0a
header[13] = 0x86
header[14] = 0x33
header[15] = 0xf1
header[16] = 0x0a
header[17] = 0x86
header[18] = 0x33
header[19] = 0x76
print("Checksum is: %x" % (checksum.ip_checksum(header, len(header)),))
print("Should be BD92")
Here's the source code:
def ip_checksum(ip_header, size):
cksum = 0
pointer = 0
while size > 1:
cksum += int((str("%02x" % (ip_header[pointer],)) +
str("%02x" % (ip_header[pointer+1],))), 16)
size -= 2
pointer += 2
if size:
cksum += ip_header[pointer]
cksum = (cksum >> 16) + (cksum & 0xffff)
cksum += (cksum >>16)
return (~cksum) & 0xFFFF
Points of Interest
If you find any mistakes feel free to let me know and I'll fix it up .