-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchecksum.py
32 lines (25 loc) · 989 Bytes
/
checksum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/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