Trying to wrap my head around a piece of code i found for Scapy.
from scapy.utils import RawPcapReader
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, TCP
for pkt_data, pkt_metadata in RawPcapReader(file_name):
ether_pkt = Ether(pkt_data)
if 'type' not in ether_pkt.fields:
# LLC frames will have 'len' instead of 'type'.
# We disregard those
continue
if ether_pkt.type != 0x0800:
# disregard non-IPv4 packets
continue
ip_pkt = ether_pkt[IP]
The part which confuses me is my object ether_pkt is assigned to class Ether but something changes with ip_pkt = ether_pkt[IP]
What is happening here ?
One funny thing with python is that you can bind all operators to do custom things. For instance, you can create an object where the +
operator does something completely different.
In scapy, the bracket operator was implemented to mean "get the following layer" from the packet. Here you are dissecting a packet by specifying the first layer: Ethernet. This will dissect also dissect all the sub-layers, among which IP.
pkt = Ether()/IP()
pkt[IP] # Only the IP layer
d = bytes(pkt) # The full packet as bytes
Ether(d)[IP] # Dissect the packet, get the IP layer
More infos over https://scapy.readthedocs.io/en/latest/usage.html