I have layer
and field
as variables. How can I get the field value?
#packet is just a sniff() packet
layer = "IP"
field = "src"
# I need something like
fieldValue = packet[layer].field
# or
fieldValue = packet[layer].getfieldval(field)
print("Layer: ", layer, " Field: ", field, " Value: ", fieldValue)
#Output- Layer: IP Field: src Value: 192.168.1.1
Let's say that we are sniffing packets with scapy and want to look at the values inside. Much of this is a matter of using the scapy documentation to find what attributes each layer has. You can also do this in your python/scapy interpreter with dir(packet)
to see what attributes and methods it has. For example:
>>> dir(packet)
...
'show',
'show2',
'show_indent',
'show_summary',
'sniffed_on',
'sprintf',
'src',
...
To dynamically get the source attribute from the packet, we need to use getattr function, which can get both methods and attributes from an object.
# Required if you are not using the scapy interpreter
from scapy.all import sniff, IP
layer = "IP"
field = "src"
# Sniff 4 packets, filtering for packets with an IP layer
packet_list = sniff(filter="ip", count=4)
# Choose first packet arbitrarily
packet0 = packet_list[0]
# We can get the attribute reflexively because python allows it
field_value = getattr(packet0[layer], field)
# Print this information
print("Layer: ", layer, " Field: ", field, " Value: ", field_value)
---
> Layer: IP Field: src Value: 192.168.1.246