You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scapy的sniff函数中使用多个过滤器实现网络抓包?

How to Capture Multiple Protocols with Scapy's Sniff Function

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 udp in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:59:58