How to verify if a packet in Scapy has a TCP layer

farfalla picture farfalla · Feb 28, 2014 · Viewed 8.1k times · Source

I want to know how can I verify that a packet I received from the sr1() function in Scapy contains a TCP layer, in order to do some treatment on the TCP flags.

Answer

RyPeck picture RyPeck · Feb 28, 2014

You have two options, the in operator is one.

>>> TCP in pkt
True
>>> if TCP in pkt:
...     # Handle TCP Flags

Packet objects in Scapy also have a function called haslayer().

>>> pkt = IP()/TCP()
>>> pkt.haslayer(TCP)
1
>>> pkt2 = IP()/UDP()
>>> pkt2.haslayer(TCP)
0
>>> Packet.haslayer.__doc__
'true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.'