Home > Back-end >  Capturing packets in python 3
Capturing packets in python 3

Time:04-17

How can I capture packets with pithon 3? I want to emphasize that my goal is not to listen to traffic, but to capture it. So, in the scapy module there is a sniff function that allows you to listen to the traffic, but not capture it. Is there a function that allows me to capture a packet so that I can determine whether to send it or not?

CodePudding user response:

To capture traffic you just save what you sniffed.

from scapy.all import *
wrpcap("somefile.pcap", sniff(iface='yourInterface', count=100))

CodePudding user response:

The best way to capture packets and not only to sniff them is by using pydivert.

import pydivert

# Capture only TCP packets to port 80, i.e. HTTP requests.
w = pydivert.WinDivert("tcp.DstPort == 80 and tcp.PayloadLength > 0")

w.open()  # packets will be captured from now on

packet = w.recv()  # read a single packet
print(packet)
w.send(packet)  # re-inject the packet into the network stack

w.close()  # stop capturing packets

This will capture all the tcp traffic on the destination port 80. You need to filter only the traffic you want to capture. Be also aware that by doing this the performance network will may vary depending on what you are doing with the captured packets.

  • Related