Scapy is an incredible tool when it comes to playing with the network. As it is
written on its official website, Scapy can replace a majority
of network tools such as nmap, hping and tcpdump.
One of the features offered by Scapy is to sniff the network packets passing
through a computer's NIC. Below is a small example:
from scapy.all import *
interface = "eth0"
def print_packet(packet):
ip_layer = packet.getlayer(IP)
print("[!] New Packet: {src} -> {dst}".format(src=ip_layer.src, dst=ip_layer.dst))
print("[*] Start sniffing...")
sniff(iface=interface, filter="ip", prn=print_packet)
print("[*] Stop sniffing")
This little sniffer displays the source and the destination of all packets
having an IP layer:
$ sudo python3 sniff_main_thread.py
[*] Start sniffing...
[!] New Packet: 10.137.2.30 -> 10.137.2.1
[!] New Packet: 10.137.2.30 -> 10.137.2.1
[!] New Packet: 10.137.2.1 -> 10.137.2.30
[!] New Packet: 10.137.2.1 -> 10.137.2.30
[!] New Packet: 10.137.2.30 -> 216.58.198.68
[!] New Packet: 216.58.198.68 -> 10.137.2.30
[!] New Packet: 10.137.2.30 -> 216.58.198.68
[!] New Packet: 10.137.2.30 -> 216.58.198.68
[!] New Packet: 216.58.198.68 -> 10.137.2.30
[!] New Packet: 216.58.198.68 -> 10.137.2.30
[!] New Packet: 10.137.2.30 -> 216.58.198.68
[!] New Packet: 10.137.2.30 -> 216.58.198.68
[!] New Packet: 216.58.198.68 -> 10.137.2.30
[!] New Packet: 10.137.2.30 -> 216.58.198.68
^C[*] Stop sniffing
It will continue to sniff network packets until it receives a keyboard
interruption (CTRL+C
).