Capturing packets with pcapy

We can use the open_live method in the pcapy interface to capture packets in a specific device and we can specify the number of bytes per capture and other parameters such as promiscuous mode and timeout.

In the following example, we'll count the packets that are capturing the eht0 interface.

You can find the following code in the capturing_packets.py file:

#!/usr/bin/pythonimport pcapydevs = pcapy.findalldevs()print(devs)#  device, bytes to capture per packet, promiscuous mode, timeout (ms)cap = pcapy.open_live("eth0", 65536 , 1 , 0)count = 1while count:    (header, payload) = cap.next()    print(count)    count = count + 1

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.