python计算UDP校验和
import os
binFileName = input("input bin file name:")
# binFileName = "file/1.bin"
binFile = open(binFileName, 'rb')
fileSize = os.path.getsize(binFileName)
pos = binFile.tell()
if fileSize != 512 and fileSize != 896:
print("The file size is not 512 or 896")
quit()
# 4 sync + 6 aos + 32 insert + 2 mpdu + 4 encap + 4 IPE = 52
binFile.seek(52)
data = binFile.read(2)
value = int.from_bytes(data, byteorder='big', signed=False)
if value >> 12 != 0x6:
print("IPv6 head is not 0x6 version")
quit()
# IPv6 payload length
binFile.seek(56)
data = binFile.read(2)
payloadLength = int.from_bytes(data, byteorder='big', signed=False)
if (fileSize == 512 and payloadLength > 512) or (fileSize == 896 and payloadLength > 896):
print("IPv6 payload length exceeds frame size")
quit()
checkSum1 = 0
# UDP header 8 bytes, skip 2 bytes check sum
loop = 92
binFile.seek(92)
while loop <= 92 + 6 - 2:
data = binFile.read(2)
value = int.from_bytes(data, byteorder='big', signed=False)
checkSum1 = checkSum1 + value
loop = loop + 2
# UDP data xx bytes
loop = 100
binFile.seek(100)
while loop <= 100 + payloadLength - 8 - 2:
data = binFile.read(2)
value = int.from_bytes(data, byteorder='big', signed=False)
checkSum1 = checkSum1 + value
loop = loop + 2
checkSum2 = 0
# IPv6 pseudo header source address, destination address
loop = 60
binFile.seek(60)
while loop <= 60 + 32 - 2:
data = binFile.read(2)
value = int.from_bytes(data, byteorder='big', signed=False)
checkSum2 = checkSum2 + value
loop = loop + 2
checkSum2 = checkSum2 + 0x11
checkSum2 = checkSum2 + payloadLength
checkSum = checkSum1 + checkSum2
while checkSum & 0xFF0000 != 0:
carry = int(checkSum / 65536)
checkSum = (checkSum & 0xFFFF) + carry
checkSum = 65535 - checkSum
print("UDP check sum is %x" % checkSum)