我需要计算IP数据包的校验和,如http://www.faqs.org/rfcs/rfc1071.html中所述。在Python中计算IP校验和
我已经下面的代码:
#!/usr/bin/python
import struct
data = "45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1"
# a test for the checksum calculation
def _checksum(data):
#calculate the header sum
ip_header_sum = sum(struct.unpack_from("6H", data))
#add the carry
ip_header_sum = (ip_header_sum & 0xFFFF) + (ip_header_sum >> 16 & 0xFFFF)
#invert the sum, python does not support inversion (~a is -a + 1) so we have to do
#little trick: ~a is the same as 0xFFFF & ~a
ip_header_sum = ~ip_header_sum & 0xFFFF
return ip_header_sum #should return 0 if correct
data = data.split()
data = map(lambda x: int(x,16), data)
data = struct.pack("%dB" % len(data), *data)
print " ".join(map(lambda x: "0x%02x" % ord(x), data))
print "Checksum: 0x%04x" % _checksum(data)
它与我所使用Wireshark捕获和一个包,必须具有正确的校验和,因此应计算为0
不幸的是,结果是0x6524。 有趣的是,对于每个正确的数据包,结果始终为0x6524 ...
谁发现错误?
编辑,以使误差更清晰 * *编辑
Python的说:'NameError:全局名称 '一个' 不defined'。你的意思是'ip_header_sum =〜ip_header_sum&0xFFFF'? – Seth 2010-10-16 17:51:02
对不起。现在已经纠正了。 – Simon 2010-10-16 18:53:00