Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Scapy:使用后期构建功能在构建后更新字段_Python_Layer_Packet_Scapy - Fatal编程技术网

Python Scapy:使用后期构建功能在构建后更新字段

Python Scapy:使用后期构建功能在构建后更新字段,python,layer,packet,scapy,Python,Layer,Packet,Scapy,我正在尝试在Scapy中构建一个自己的层,其中包含一个“LengthField”。此字段应包含此层的总大小+后面的所有内容。 我知道“post_build”方法是我实现这一目标所需要的,我试图理解它在Scapy文档中的使用方式,但我不理解它 假设我有一层 class MyLayer(Packet): name = "MyLayer" fields_desc = [ ByteField("SomeField", 1),

我正在尝试在Scapy中构建一个自己的层,其中包含一个“LengthField”。此字段应包含此层的总大小+后面的所有内容。 我知道“post_build”方法是我实现这一目标所需要的,我试图理解它在Scapy文档中的使用方式,但我不理解它

假设我有一层

class MyLayer(Packet):

    name = "MyLayer"
    fields_desc = [
                   ByteField("SomeField", 1),
                   IntField("LengthField", 0)
                   ]

我需要如何修改该类,以便它可以在构建时自动更新LengthField?

post\u dissect
中用新的
MyLayer
的长度固定字段大小。请注意,您不能使用
len(str(self))
进行长度计算,因为由于
str()
调用
do_dissect
,最终将导致无休止的递归

class MyLayer(Packet):
    name = "MyLayer"
    fields_desc = [
                   ByteField("SomeField", 1),
                   LenField("LengthField", None),   # calcs len(pkt.payload)
                   ]
    def post_dissect(self, s):
        self.LengthField += len(str(self.__class__()))     # add this layer size by creating a new temporary layer and calculating its size.
        return Packet.post_dissect(self, s)
该值将在
show2()时计算

导致

###[ MyLayer ]###
  SomeField = 1
  LengthField= 9
###[ Raw ]###
     load      = 'hihiii'
其中9=6字节有效负载(原始)+1字节(SomeField)+2字节(LenField with fmt=“H”==shortInt==2字节)

您可以参考源代码中的一些示例:

class HCI_Command_Hdr(Packet):
    name = "HCI Command header"
    fields_desc = [XLEShortField("opcode", 0),
                   ByteField("len", None), ]

    def post_build(self, p, pay):
        p += pay
        if self.len is None:
            p = p[:2] + struct.pack("B", len(pay)) + p[3:]
        return p
结果是:

>>> (HCI_Command_Hdr()/"1234567").show2()
###[ HCI Command header ]### 
  opcode= 0x0
  len= 7
###[ Raw ]### 
     load= '1234567'
您可以打印
p
pay
以了解代码:

 p[:2] + struct.pack("B", len(pay)) + p[3:]

然后,修改它以满足您的需要。

谢谢,我也找到了一个使用
post\u build()
的解决方案,在这个解决方案中,长度然后添加到二进制级别,但这个解决方案似乎更好。不,post\u dissect是用于剥离(获取数据包时),而不是在构建数据包时
>>> (HCI_Command_Hdr()/"1234567").show2()
###[ HCI Command header ]### 
  opcode= 0x0
  len= 7
###[ Raw ]### 
     load= '1234567'
 p[:2] + struct.pack("B", len(pay)) + p[3:]