添加新数据包 scapy:具有随机位置字段的奇怪错误

Adding new packet scapy: strange bug with random position fields

这是奇怪的行为:

ReturnCodeEnum = {
    0x1: "vardiag",
    0x2: "gambit"
}

TransportSizeEnum = {
    0x10: "No error",
    0x11: "Error: ressource not find",
    0x21: "Error: busy"
}


class UNSPECIFIED(Packet):
    name = "UNSPECIFIED"
    fields_desc = {
        ByteEnumField("returncode", 0x00, ReturnCodeEnum),
        ByteEnumField("transportsize", 0x0, TransportSizeEnum),
        FieldLenField("len", None, length_of="datapart"),
        StrLenField("datapart", "", length_from=lambda pkt: pkt.len)
    }


In [21]: a = UNSPECIFIED()

In [24]: a.show()
###[ UNSPECIFIED ]###
  len       = None
  returncode= 0
  datapart  = ''
  transportsize= 0

In [25]: # Reloading the file
In [26]: a = UNSPECIFIED()

In [27]: a.show()
###[ UNSPECIFIED ]###
  datapart  = ''
  transportsize= 0
  len       = None
  returncode= 0

In [28]: a.show2()
###[ UNSPECIFIED ]###
  datapart  = '\x00\x00\x00\x00'
  transportsize= 0
  len       = 0
  returncode= 0

In [29]:
In [30]: a = UNSPECIFIED()

In [33]: a.show()
###[ UNSPECIFIED ]###
  len       = None
  returncode= 0
  datapart  = ''
  transportsize= 0

In [34]: a.show2()
###[ UNSPECIFIED ]###
  len       = 0
  returncode= 0
  datapart  = ''
  transportsize= 0

不遵守数据包字段位置。每次我重新加载此源时,字段的位置都会发生变化。我构建了很多 scapy 数据包,但这是我第一次遇到这个错误。也许我没有正确使用关联 FieldLenField/StrLenField ?

"Every time I reload this source, field's positions are changing"

我可能是错的,但只要您的 key/value 对保持不变,我认为您所看到的是字典本质上无序的结果。来自 the docs:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)

一个简单的测试:

dict_order_test.py

my_dict = {"a":1, "b":2, "c":3}
print (my_dict)

终端输出:

$ python3 dict_order_test.py 
{'b': 2, 'c': 3, 'a': 1}
$ python3 dict_order_test.py 
{'b': 2, 'a': 1, 'c': 3}
$ python3 dict_order_test.py 
{'c': 3, 'a': 1, 'b': 2}
$ python3 dict_order_test.py 
{'c': 3, 'a': 1, 'b': 2}

稍微修改一下我上面写的内容,字典 有某种顺序,但你不能指望它,每次你 运行 一个脚本。如果我没记错的话,顺序取决于它们包含的数据类型以及它们如何在内部被 Python 散列。有时顺序不会改变,有时会改变;无论哪种方式,它都是不可靠的,所以如果重要,请使用 listOrderedDict