How to check for presence of a layer in a scapy packet?

Mr. Shickadance picture Mr. Shickadance · Apr 4, 2011 · Viewed 21.3k times · Source

How do I check for the presence of a particular layer in a scapy packet? For example, I need to check the src/dst fields of an IP header, how do I know that a particular packet actually has an IP header (as opposed to IPv6 for instance).

My problem is that when I go to check for an IP header field, I get an error saying that the IP layer doesn't exist. Instead of an IP header, this particular packet had IPv6.

pkt = Ether(packet_string)
if pkt[IP].dst == something:
  # do this

My error occurs when I try to reference the IP layer. How do I check for that layers existence before attempting to manipulate it?

Thanks!

Answer

jliendo picture jliendo · Apr 5, 2011

You should try the in operator. It returns True or False depending if the layer is present or not in the Packet.

root@u1010:~/scapy# scapy
Welcome to Scapy (2.2.0-dev)
>>> load_contrib("ospf")
>>> pkts=rdpcap("rogue_ospf_hello.pcap")
>>> p=pkts[0]
>>> IP in p
True
>>> UDP in p
False
>>>
root@u1010:~/scapy#