Making magic with the network stack
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.4 KiB

  1. # Code has been taken from https://www.codeproject.com/Tips/460867/Python-Implementation-of-IP-Checksum
  2. # Example is provided at https://www.thegeekstuff.com/2012/05/ip-header-checksum/
  3. # For now, manually changing values in the header field to compute IP checksum.
  4. def ip_checksum(ip_header, size):
  5. cksum = 0
  6. pointer = 0
  7. #The main loop adds up each set of 2 bytes. They are first converted to strings and then concatenated
  8. #together, converted to integers, and then added to the sum.
  9. while size > 1:
  10. cksum += int((str("%02x" % (ip_header[pointer],)) +
  11. str("%02x" % (ip_header[pointer+1],))), 16)
  12. size -= 2
  13. pointer += 2
  14. if size: #This accounts for a situation where the header is odd
  15. cksum += ip_header[pointer]
  16. cksum = (cksum >> 16) + (cksum & 0xffff)
  17. cksum += (cksum >>16)
  18. return (~cksum) & 0xFFFF
  19. if __name__=="__main__":
  20. header = {}
  21. header[0] = 0x45
  22. header[1] = 0x00
  23. header[2] = 0x00
  24. header[3] = 0x28
  25. header[4] = 0x00
  26. header[5] = 0x02
  27. header[6] = 0x00
  28. header[7] = 0x00
  29. header[8] = 0x28
  30. header[9] = 0x06
  31. header[10] = 0xfd
  32. header[11] = 0x5f
  33. header[12] = 0xc0
  34. header[13] = 0xa8
  35. header[14] = 0x0a
  36. header[15] = 0x14
  37. header[16] = 0xc0
  38. header[17] = 0xa8
  39. header[18] = 0x0a
  40. header[19] = 0x0a
  41. print("Checksum is: %x" % (ip_checksum(header, len(header)),))