Namaste Friends,

### Today, In this tutorial I am going to show you how we can calculate IPv4 packet checksum in python

#### Introduction

Calculating IPv4 checksum is very hard and difficult concept for many guys because Networking concept is very big and complex. Hence, In networking protocols packets concept, the IPv4 checksum is an important topic to understand Because IPv4 checksum is One type of the hash value of complete IPv4 packet that verifies the completeness and status of IP checksum. During a TCP  communication, Client Always sends IP checksum values into the IP packet so that the packet receiving server application can analyze the packet value and recalculate the checksum to verify the status of the packet.
IP checksum helps server and client machine to detect corrupt packets.

#### How it's going to work?

Well, I am not going to make this tutorial lengthy.

Check Below Links To Understand The Theory Behind Calculating Checksum and Etc.

Calculate IPv4 Packet Checksum Theory

#### Example Codes

Here, is my python codes for calculating TCP packet checksum.

```#!/usr/bin/python
import socket
import struct
import binascii

class IPPacket:

###################################################
#            <---Code skipped -->                 #
###################################################

def chksum(self, msg):
s = 0       # Binary Sum

# loop taking 2 characters at a time
for i in range(0, len(msg), 2):
if (i+1) < len(msg):
a = ord(msg[i])
b = ord(msg[i+1])
s = s + (a+(b << 8))
elif (i+1)==len(msg):
s += ord(msg[i])
else:
raise "Something Wrong here"

# One's Complement
s = s + (s >> 16)
s = ~s & 0xffff

return s

###################################################
#            <---Code skipped -->                 #
###################################################
```

For Complete Codes Of This Script. Check Below Link

Code To Create IPv4 Packet In Python

Written By:
SSB