校验和udp计算python [英] checksum udp calculation python

查看:181
本文介绍了校验和udp计算python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算要发送的UDP标头数据包的校验和:

I'd like to calculate the checksum of an UDP header packet I want to send:

packetosend = """60 00 00 00 00 24 3a 40 20 02 c0 a8 01 50 00 01 00 00 
00 00 00 00 09 38 20 02 c0 a8 01 50 00 01 00 00 00 00 00 00 09 6f"""

所以我需要加入这个utf-16(不是问题)并计算特定数据包的校验和.我该怎么办?

so I need to join this utf-16 (not a problem) and calculate the checksum of this specific packet. How can I do that?

谢谢!

是的,这是ICMPv6数据包的IPv6标头,无论如何我想知道的是公式及其工作原理.

Yes it's an IPv6 header for an ICMPv6 packet, anyways what I would like to know is the formula, and how it works.

我将举另一个带有ICMP ping回显(v4)数据包的示例:

I'll give another example with an ICMP ping echo (v4) packet:

packet = """
08 00 d1 15 76 0c 00 07 bf d3 55 4a ad b5 03 00   // "d1 15" is the packet checksum 
08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17
18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27
28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37"""

谢谢.

推荐答案

对我来说,这看起来不像UDP数据包.看起来像是ICMPv6数据包的IPv6标头,但该数据包的实际有效载荷丢失了.

This doesn't look like a UDP packet to me. It looks like an IPv6 header for an ICMPv6 packet, but the actual payload of the packet is missing.

IPv6标头不包含校验和.

对于 ICMP ,校验和是"16位元的补码"从类型字段开始的ICMP消息的补码和." 一个补码算法涉及进位的特殊处理.

For ICMP, the checksum is "the 16-bit one's complement of the one's complement sum of the ICMP message starting with the Type field." One's complement arithmetic involves special treatment of the carry bit.

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

为了计算正确的校验和,您当然必须从正确的msg开始,这意味着至少首先将校验和字段清零,并且可能还需要添加虚拟标头",具体取决于您使用的协议重新使用.

In order to calculate the right checksum, of course you have to start with the right msg, which means at least zeroing out the checksum field first and may also require adding "virtual headers", depending on the protocols you're using.

这篇关于校验和udp计算python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆