Question
Answer and Explanation
To use Scapy to sniff packets for 10 seconds, you can utilize the sniff
function with the timeout
parameter. Here’s how you can do it:
1. Installation:
First, ensure that you have Scapy installed. You can install it using pip:
pip install scapy
2. Basic Sniffing Code:
Here's the Python code using Scapy to capture packets for 10 seconds:
from scapy.all import
def packet_callback(packet):
print(packet.summary())
if __name__ == '__main__':
print("Sniffing packets for 10 seconds...")
packets = sniff(timeout=10, prn=packet_callback)
print(f"Captured {len(packets)} packets.")
Explanation:
- We import everything from the Scapy library using from scapy.all import
.
- A packet_callback
function is defined which is called every time a packet is received. This example prints a summary of the packet.
- The sniff
function is called with a timeout
parameter set to 10
, which specifies that the sniffing should run for 10 seconds. The prn
parameter specifies the callback function to be used every time a packet is sniffed.
- The number of captured packets is printed after the 10 seconds have passed.
3. Running the code:
Execute the Python script. You may need administrator/root privileges to capture packets, because it involves directly interacting with the network interface.
4. Optional interface specification:
If you need to sniff on a specific interface, you can specify that interface with the iface
parameter. For example, to sniff on the eth0
interface:
packets = sniff(timeout=10, prn=packet_callback, iface="eth0")
5. Filtering packets:
You can also filter the packets you capture using the filter
parameter. For example, to sniff only TCP packets:
packets = sniff(timeout=10, prn=packet_callback, filter="tcp")
By using these parameters, you can customize the sniffing process to suit your needs, whether by time, specific network interface, or protocol.