Sniffing packets
Scapy has a sniff()
function that we can use for getting packets from the network. But Scapy's built-in sniff()
function is a bit slow and may skip some packets. It is better to use tcpdump
when the sniffing speed is important.
How to do it...
Here are the steps to write a sniffer with scapy
module:
- Create a file called
scapy-sniffer.py
and open it with your editor. - As usual, import the required modules for the script:
import sysfrom scapy.all import *
- Then, define the variables required. Here we need to define the
interface
to sniff:
interface = "en0"
You can get the interface
to be used with the help of the ifconfig
command in Linux and macOS:

- Now we can write a function to handle the sniffed packets, which will be provided as the callback function for the sniffer:
def callBackParser(packet):if IP in packet: source_ip = packet[IP].src destination_ip = packet[IP].dstif packet.haslayer(DNS) and packet.getlayer(DNS).qr == 0: print("From : " + str(source_ip) + " to -> " + str(destination_ip...