# from scapy inet.py
if struct.pack("H", 1) == b"\x00\x01": # big endian
checksum_endian_transform = lambda chk: chk
else:
checksum_endian_transform = lambda chk: ((chk >> 8) & 0xff) | chk << 8
def checksum(pkt):
if len(pkt) % 2 == 1:
pkt += b"\0"
s = sum(array.array("H", pkt))
s = (s >> 16) + (s & 0xffff)
s += s >> 16
s = ~s
return checksum_endian_transform(s) & 0xffff
def in4_chksum(proto, u, p):
"""
As Specified in RFC 2460 - 8.1 Upper-Layer Checksums
Performs IPv4 Upper Layer checksum computation. Provided parameters are:
- 'proto' : value of upper layer protocol
- 'u' : IP upper layer instance
- 'p' : the payload of the upper layer provided as a string
"""
if not isinstance(u, IP):
warning("No IP underlayer to compute checksum. Leaving null.")
return 0
if u.len is not None:
if u.ihl is None:
olen = sum(len(x) for x in u.options)
ihl = 5 + olen // 4 + (1 if olen % 4 else 0)
else:
ihl = u.ihl
ln = max(u.len - 4 * ihl, 0)
else:
ln = len(p)
psdhdr = struct.pack("!4s4sHH",
inet_pton(socket.AF_INET, u.src),
inet_pton(socket.AF_INET, u.dst),
proto,
ln)
return checksum(psdhdr + p)
【NET】UDP数据包中checksum计算
最新推荐文章于 2024-05-13 20:04:16 发布