使用wiresh的校验和icmp python

2024-04-26 22:56:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在过去的几天里,我对ICMP协议很感兴趣,我发现了一个python函数来计算它的校验和:

def carry_around_add(a, b):
    c = a + b
    return (c & 0xffff) + (c >> 16)

def checksum(msg):
   s = 0
   for i in range(0, len(msg), 2):
       w = ord(msg[i]) + (ord(msg[i+1]) << 8)
       s = carry_around_add(s, w)
   return ~s & 0xffff

print checksum("abcdefghijklmnopqrst")

在这张截获的wireshark照片中:http://memory00stack.files.wordpress.com/2013/12/resultat.png

校验和是“0xcfcb”,但我测试中的函数返回“55 245->;0xd7cd”。为什么?在

非常感谢=)


Tags: 函数inadd协议forreturndefrange
1条回答
网友
1楼 · 发布于 2024-04-26 22:56:33

wireshark转储显示ICMP校验和,但是(wikipedia):

^{bq}$

测试中校验和例程的输入只是ASCII有效负载部分。您必须提供整个ICMP输入。在


例如:

def carry_around_add(a, b):
    c = a + b
    return (c & 0xffff) + (c >> 16)

def checksum(msg):
   s = 0
   for i in range(0, len(msg), 2):
       w = ord(msg[i]) + (ord(msg[i+1]) << 8)
       s = carry_around_add(s, w)
   return ~s & 0xffff

payload_body = "abcdefghijklmnopqrst"
chk = checksum(payload_body)
print chk, '{:x}'.format(chk), '(host byte order)'

msg_type = '\x08' # ICMP Echo Request
msg_code = '\x00' # must be zero
msg_checksum_padding = '\x00\x00' # "...with value 0 substituted for this field..."
rest_header = '\x00\x01\x00\x01' # from pcap
entire_message = msg_type + msg_code + msg_checksum_padding + rest_header + payload_body
entire_chk = checksum(entire_message)
print entire_chk, '{:x}'.format(entire_chk), '(host byte order)'

当我在我的(little endian)机器上运行这个程序时,我得到:

^{pr2}$

相关问题 更多 >