Filtering Incoming Packets

Learn how to apply filtering on packets received using Scapy’s sniff function for further analysis.

Introduction to filtering with Scapy

Previously, we used Scapy’s sniff function to monitor network traffic. Instead of sending packets and looking for responses, sniff provides access to all traffic that is visible to the system.

However, we might not always want to inspect all types of network traffic. For example, if we’re implementing a honeypot or a server, we may want to focus on certain types of traffic. For this, we’ll need to filter the traffic that Scapy sniffs and only analyze certain types of traffic.

Filtering traffic by protocol

As mentioned previously, sniff can take various arguments, and one of these arguments is the filter command. This argument allows us to define the types of packets that we want to send on to our packet analysis function.

Scapy uses Berkeley Packet Filter (BPF) syntax to define filters for the sniff function’s filter argument. One of the advantages of using filter is that it provides faster, more efficient filtering than passing all traffic to the function and filtering it manually.

One of the simplest BPF filters is filtering by protocol. To do so, specify the protocol to be included. For example, the following code block filters traffic for TCP packets:

Get hands-on with 1200+ tech skills courses.