Scapy:向fields_desc添加更多字段

时间:2015-06-24 08:54:05

标签: python scapy packets

我正在尝试创建一个新协议。问题是,需要动态地向fields_desc添加更多字段,但我不知道如何实现这一点。 在Scapy文档中,我读到Scapy中的一个层实际上只是一个字段列表,可以操作,但Scapy似乎不喜欢以下内容:

>>> class SomePacket(Packet):
...         
...     name = "SomePacket"
...     fields_desc = [ IntField("Number",0) ]
...             
...     def add_IntField(self, name, value):
...         self.fields_desc.append(IntField(name, value))
... 
>>> packet = SomePacket()
>>> ls(packet)
Number     : IntField             = 0               (0)
>>> packet.add_IntField("X",1)
>>> ls(packet)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/scapy/packet.py", line 1212, in ls
    print "%-10s : %-20s = %-15s (%s)" % (f.name, f.__class__.__name__, repr(getattr(obj,f.name)), repr(f.default))
  File "/usr/lib/python2.7/dist-packages/scapy/packet.py", line 176, in __getattr__
    fld,v = self.getfield_and_val(attr)
  File "/usr/lib/python2.7/dist-packages/scapy/packet.py", line 172, in getfield_and_val
    return self.payload.getfield_and_val(attr)
  File "/usr/lib/python2.7/dist-packages/scapy/packet.py", line 1057, in getfield_and_val
    raise AttributeError(attr)
AttributeError: X
>>> packet = SomePacket()
>>> ls(packet)
Number     : IntField             = 0               (0)
X          : IntField             = 1               (1)

因此,当我在添加字段后首次尝试显示数据包内容时,它不起作用。但是,如果我再次创建数据包,属性突然出现。我做错了什么?

1 个答案:

答案 0 :(得分:1)

你不应该这样做。当您创建新的SomePacket对象时,__init__()的{​​{1}}函数会使用Packet列表初始化许多其他内容。动态地向fields_desc添加新值会导致不一致,从而产生给定的错误。

一种解决方案是将fields_desc函数更改为add_IntField并在创建新对象之前添加所需的字段,如下所示:

classmethod