13,042,421 members (118,351 online)
Tip/Trick
alternative version

#### Stats

13K views
4 bookmarked
Posted 17 Sep 2012

# Python Implementation of IP Checksum

, 18 Sep 2012
 Rate this:
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:

```import checksum

print("Should be BD92")```

Here's the source code:

```#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:        checksum.py
#
# Author:      Grant Curell
#
# Created:     16 Sept 2012
#
# Description: Calculates the checksum for an IP header
#-------------------------------------------------------------------------------

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],)) +
size -= 2
pointer += 2
if size: #This accounts for a situation where the header is odd

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 https://www.codeproject.com/script/Forums/Images/smiley_biggrin.gif.

## Share

 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 GHIH. More info at grantcurell.com.

## You may also be interested in...

 First Prev Next
 Too complex to be readable. RPGillespie27-Jun-13 9:26 RPGillespie 27-Jun-13 9:26
 Re: Too complex to be readable. haitk110221-Oct-13 0:09 haitk1102 21-Oct-13 0:09
 Re: Too complex to be readable. haitk110221-Oct-13 0:15 haitk1102 21-Oct-13 0:15
 Last Visit: 31-Dec-99 18:00     Last Update: 20-Jul-17 8:57 Refresh 1