如何在Scapy的sniff函数中使用多个过滤器实现网络抓包?
Hey there! I see you're building a packet capture app with Scapy and a GUI, and you're stuck on capturing multiple protocols at the same time. Let's fix that!
Why Your Current Approaches Aren't Working
- First method issue: You used
tcp and udpin your filter—but a single packet can't be both TCP and UDP at the same time! That's why you weren't getting the results you wanted; no packet matches both protocols, so the filter effectively captured nothing. - Second method issue: Running two separate
sniff()calls means you're capturing TCP for 5 seconds, then UDP for another 5 seconds—not capturing both protocols simultaneously.
The Correct Way to Capture Multiple Protocols
Scapy uses BPF (Berkeley Packet Filter) syntax for its filter parameter, just like tools like Wireshark or tcpdump. To capture packets that match any of your target protocols, use the or operator instead of and.
Here's the fixed code:
import scapy.all as scapy # Capture both TCP and UDP packets for 5 seconds capture = scapy.sniff(filter="tcp or udp", timeout=5) # Verify the captured packets for pkt in capture: print(f"Captured {pkt.name} packet") pkt.summary() # Quick overview of packet content
Extending to More Protocols (Perfect for Your GUI)
If your GUI lets users select multiple protocols (like TCP, UDP, ICMP, etc.), you can dynamically build the filter string by joining selected options with or. This makes it easy to adapt to user input:
import scapy.all as scapy # Example: List of protocols selected in your GUI selected_protocols = ["tcp", "udp", "icmp"] # Build the filter string dynamically filter_string = " or ".join(selected_protocols) # Start capturing with the combined filter capture = scapy.sniff(filter=filter_string, timeout=10) # Process results print(f"Captured {len(capture)} packets matching: {filter_string}")
This approach will capture all packets that match any of the selected protocols at the same time, which is exactly what you need for your app.
内容的提问来源于stack exchange,提问作者HumorGuy

