任何更好的代码来定义通用TLV初始化为不同类型

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

也许更多这是基于面向对象的编程 -

将通用TLV定义为

 class MYTLV(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, defaultTLV_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]

我有很多相同形式但有不同类型的TLV。我怎样才能有更好的代码来减少代码中的代码

     class newTLV(MYTLV):
          some code to say or initiaze type field of this newTLV to newTLV_enum
     ....

所以后来我可以使用 -

     PacketListField('tlvlist', [], newTLV(fields.type=newTLV_enum))

除类型字段的字典外,所有TLV都相同。

    class MYTLV1(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, TLV1_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]
   class MYTLV2(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, TLV2_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]
python object scapy tlv
1个回答
2
投票

你可以这样做:

base_fields_desc = [
    FieldLenField("length", None, fmt='B', length_of="value"),
    StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
]

def fields_desc_with_enum_type(enum_type):
    fields_desc = base_fields_desc[:]
    fields_desc.insert(0, ByteEnumField("type", 0x1, enum_type))
    return fields_desc


class MYTLV1(Packet):
    fields_desc = fields_desc_with_enum_type(TLV1_enum)

class MYTLV2(Packet):
    fields_desc = fields_desc_with_enum_type(TLV2_enum)
© www.soinside.com 2019 - 2024. All rights reserved.