以下代码示例展示了如何使用 Scapy 构造一个 ARP 数据包。
#!/usr/bin/env python3
from scapy.all import *

E = Ether()
A = ARP()
A.op = 1     # 1 为 ARP 请求; 2 为 ARP 响应

pkt = E/A
sendp(pkt)

上述程序构建并发送了一个 ARP 数据包。请设置必要的属性来构建正确的 ARP 包。我们可以通过 ls(ARP) 和 ls(Ether) 查看 ARP 和 Ether 类的属性名称。如果某个属性没有被设置,Scapy 会使用默认值(参见输出的第三列):
$ python3
>>> from scapy.all import *

>>> ls(Ether)
dst        : DestMACField                        = (None)
src        : SourceMACField                      = (None)
type       : XShortEnumField                     = (36864)

>>> ls(ARP)
hwtype     : XShortField                         = (1)
ptype      : XShortEnumField                     = (2048)
hwlen      : ByteField                           = (6)
plen       : ByteField                           = (4)
op         : ShortEnumField                      = (1)
hwsrc      : ARPSourceMACField                   = (None)
psrc       : SourceIPField                       = (None)
hwdst      : MACField                            = ('00:00:00:00:00:00')
pdst       : IPField                             = ('0.0.0.0')
Last modified: Wednesday, 7 May 2025, 8:37 AM