# Import required packages from scapy.all import * # Define a packet with a string field using FieldLenField class MyPacket(Packet): fields_desc = [ FieldLenField("string_len", None, fmt="H"), StrLenField("data_str", "", length_from=lambda pkt:pkt.string_len) ] # Create an instance of the packet and set the string field to a value pkt = MyPacket(string_len=5, data_str="Hello") # Print the packet summary print(pkt.summary())
# Import required packages from scapy.all import * # Define a packet with a list field using FieldLenField class MyPacket(Packet): fields_desc = [ FieldLenField("list_len", None, fmt="H"), FieldListField("data_list", None, StrLenField("", "", length_from=lambda pkt:pkt.list_len)) ] # Create an instance of the packet and set the list field to a value pkt = MyPacket(list_len=3, data_list=["foo", "bar", "baz"]) # Print the packet summary print(pkt.summary())In this example, we define another custom packet class `MyPacket` that contains a `list_len` field of type `FieldLenField` and a `data_list` field of type `FieldListField`. The `list_len` field specifies the number of strings in `data_list`. The `length_from` parameter is used to dynamically calculate the length of the list based on the value of `list_len`. We create an instance of `MyPacket` and set the `list_len` field to 3 and the `data_list` field to ["foo", "bar", "baz"]. Finally, we print a summary of the packet. Overall, we can see that scapy.fields.FieldLenField is an essential field type in Scapy, which can be used to dynamically calculate the length of a field, based on any other field present in the same packet.