Advertisement
mdelatorre

Internet Checksum in Python

Feb 17th, 2016
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. # An Internet checksum algorithm using Python.
  2.  
  3. # This program is licensed under the GPL; see LICENSE for details.
  4.  
  5. # This procedure can be used to calculate the Internet checksum of
  6. # some data.  It is adapted from RFC 1071:
  7. #
  8. # ftp://ftp.isi.edu/in-notes/rfc1071.txt
  9. #
  10. # See also:
  11. #
  12. # http://www.netfor2.com/ipsum.htm
  13. # http://www.netfor2.com/checksum.html
  14.  
  15. def ichecksum(data, sum=0):
  16.     """ Compute the Internet Checksum of the supplied data.  The checksum is
  17.    initialized to zero.  Place the return value in the checksum field of a
  18.    packet.  When the packet is received, check the checksum, by passing
  19.    in the checksum field of the packet and the data.  If the result is zero,
  20.    then the checksum has not detected an error.
  21.    """
  22.     # make 16 bit words out of every two adjacent 8 bit words in the packet
  23.     # and add them up
  24.     for i in range(0,len(data),2):
  25.         if i + 1 >= len(data):
  26.             sum += ord(data[i]) & 0xFF
  27.         else:
  28.             w = ((ord(data[i]) << 8) & 0xFF00) + (ord(data[i+1]) & 0xFF)
  29.             sum += w
  30.  
  31.     # take only 16 bits out of the 32 bit sum and add up the carries
  32.     while (sum >> 16) > 0:
  33.         sum = (sum & 0xFFFF) + (sum >> 16)
  34.  
  35.     # one's complement the result
  36.     sum = ~sum
  37.  
  38.     return sum & 0xFFFF
  39.  
  40. check = ichecksum('list\n')
  41. print check
  42. print ichecksum('list\n',check)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement