设置FieldLenField的大小

问题描述 投票:0回答:1

我想要一个1字节的 FieldLenField 以允许相应的256个项目 FieldListField,我该怎么做呢?

from scapy import *

class Foo(Packet):
    name = "Foo"
    fields_desc = [
        ShortField("id", random.getrandbits(16)),
        FieldLenField("len", None, count_of="pld"),
        FieldListField("pld", None, IPField("", "0.0.0.0"), count_from=lambda pkt: pkt.len)
    ]

谢谢您的帮助。

python scapy network-protocols
1个回答
1
投票

将FieldLenField设置为1个字节。

你需要覆盖默认的 FieldLenField,目前是 H. H 是一个 格式字 来自Python的struct库,它是一个2字节的无符号(0-65535)。要强制使用一个字节的无符号结构,请使用 B 代替。

from scapy import *

class Foo(Packet):
    name = "Foo"
    fields_desc = [
        ShortField("id", random.getrandbits(16)),
        FieldLenField("len", 0, fmt="B", count_of="pld"),
        FieldListField("pld", None, IPField("", "0.0.0.0"), 
                       count_from=lambda pkt: pkt.len)
    ]

pkt = Foo()
print(bytes(pkt))

运行这个,我们会得到2个随机的字节作为ID,1个字节作为len,看起来是这样的:

b'\x21\xea\x00'

最后一个字节是我们设置的默认0.

验证

如果我们尝试设置 len 到300,这是在区间[0,255]之外,我们会得到一个错误。

pkt.len = 300
bytes(pkt)

...<traceback>
error: ubyte format requires 0 <= number <= 255
© www.soinside.com 2019 - 2024. All rights reserved.