调用 Scapy函数

本节提供一些示例,说明如何从自己代码中的 Scapy函数中获益。

UDP校验和

下面的示例说明如何使用checksum()函数手动计算和UDP校验和。必须执行以下步骤:

  1. 按照RFC768中的描述计算UDP伪头

  2. 使用scapy和p构建一个UDP包 [UDP] CHKSUM=0

  3. 使用伪头和UDP包调用checksum()。

from scapy.all import *

# Get the UDP checksum computed by Scapy
packet = IP(dst="10.11.12.13", src="10.11.12.14")/UDP()/DNS()
packet = IP(raw(packet))  # Build packet (automatically done when sending)
checksum_scapy = packet[UDP].chksum

# Set the UDP checksum to 0 and compute the checksum 'manually'
packet = IP(dst="10.11.12.13", src="10.11.12.14")/UDP(chksum=0)/DNS()
packet_raw = raw(packet)
udp_raw = packet_raw[20:]
# in4_chksum is used to automatically build a pseudo-header
chksum = in4_chksum(socket.IPPROTO_UDP, packet[IP], udp_raw)  # For more infos, call "help(in4_chksum)"

assert(checksum_scapy == chksum)