Click here to Skip to main content
15,881,248 members
Articles / General Programming / Algorithms
Tip/Trick

Python Implementation of IP Checksum

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
18 Sep 2012CPOL 33.2K   4   3
IP checksum implementation in python

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: 

Python
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:

Python
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:        checksum.py
#
# Author:      Grant Curell
#
# Created:     16 Sept 2012
#
# Description: Calculates the checksum for an IP header
#-------------------------------------------------------------------------------
    
    
def ip_checksum(ip_header, size):
    
    cksum = 0
    pointer = 0
    
    #The main loop adds up each set of 2 bytes. They are first converted to strings and then concatenated
    #together, converted to integers, and then added to the sum.
    while size > 1:
        cksum += int((str("%02x" % (ip_header[pointer],)) + 
                      str("%02x" % (ip_header[pointer+1],))), 16)
        size -= 2
        pointer += 2
    if size: #This accounts for a situation where the header is odd
        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 Big Grin | :-D.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Grant is a specialist in computer security and networking. He holds a bachelors degree in Computer Science and Engineering from the Ohio State University. Certs: CCNA, CCNP, CCDA, CCDP, Sec+, and GCIH.

Comments and Discussions

 
QuestionToo complex to be readable. Pin
RPGillespie27-Jun-13 9:26
RPGillespie27-Jun-13 9:26 
Your code is helpful, but it isn't very readable.

Try this simpler implementation that uses just one for each loop:

#splits string into tokens every N characters
def splitN(str1,n):
    return [str1[start:start+n] for start in range(0, len(str1), n)]

#returns checksum
def ip_checksum(ip_header):

    #split into 16-bit words   
    words = splitN(''.join(ip_header.split()),4) # splits string into 16 bit words

    csum = 0;
    for word in words:
        csum += int(word, base=16)

    csum += (csum >> 16)          #add nibble
    csum = csum & 0xFFFF ^ 0xFFFF #trim to 16 bits and complement

    return csum


header = '45 00 00 e8 00 00 40 00 40 11 00 00 0a 86 33 f1 0a 86 33 76'
print "%x"%ip_checksum(header) #prints "bd92"

AnswerRe: Too complex to be readable. Pin
haitk110221-Oct-13 0:09
haitk110221-Oct-13 0:09 
GeneralRe: Too complex to be readable. Pin
haitk110221-Oct-13 0:15
haitk110221-Oct-13 0:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.