0

Maybe more of this is object oriented programming based -

defined a generic TLV as

 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)
       ]

I have many TLV of same form but have different type. How can i have better code to reduce this in codes as

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

So later I can use as -

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

All TLVs are same except for the dictionary for the type field.

    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)
       ]
mungayree
  • 313
  • 1
  • 12
  • 1
    Could you provide the code for a few of your other TLV classes? If I understand you correctly, you just want to reduce the duplication between the different classes by extracting a common base class? – Jomel Imperio May 11 '15 at 09:19
  • Yes you are correct. I modified the data above. Somehow when I press enter, it concludes the comment. – mungayree May 12 '15 at 02:18

1 Answers1

2

You could do it like this:

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)
Jomel Imperio
  • 924
  • 4
  • 16
  • For some reason at line 1 is am getting below from python -
    WARNING: No route found for IPv6 destination :: (no default route?) Traceback (most recent call last): File "tlv.py", line 5, in class MYTLV(Packet): File "/usr/lib/python2.6/site-packages/scapy/base_classes.py", line 156, in __new__ for f in current_fld: TypeError: Error when calling the metaclass bases 'property' object is not iterable
    – mungayree May 12 '15 at 06:40
  • Ah, perhaps I had assumed too much, that it would be okay to change `field_descs`. Let me edit my answer to keep more closely to your original classes. – Jomel Imperio May 12 '15 at 06:51
  • I've updated my answer with an approach that mirrors your original classes more closely. – Jomel Imperio May 12 '15 at 07:48