Capturing Network Traffic in Threads Using Scapy and Python

Network packet capture is useful only when an analyst understands what was captured, why those packets were in scope, and how the capture ends. Python and Scapy make protocol experiments approachable, but a background capture that cannot be stopped or that silently consumes all available memory is a poor monitoring tool. A controlled capture should be repeatable, finite, respectful of privacy, and explicit about the interface, filter, retention, and failure conditions.

This article focuses on one narrow problem: running a Scapy capture without blocking the rest of an application, and then shutting it down reliably. The related discussion of thread-safe downstream processing with Scapy addresses queue workers, logging, and processing pressure. A capture-lifecycle design and an analysis pipeline are related, but they are not interchangeable.

Start with an authorized capture question

A packet capture should answer a diagnostic question, not collect everything merely because the library makes it possible. On a lab machine you own, a useful question might be whether a DNS request receives a response, whether a TCP connection retries, or whether a service is using a different transport than expected. Write down the expected host or subnet, protocol, capture duration, and the exact observations that would settle the question. If the traffic includes other people’s communications, use the minimum metadata required and obtain the necessary authorization before touching a live interface.

A trace is not a view of the entire network. On a switched network, the interface sees traffic delivered to that interface, broadcast or multicast traffic, and anything legitimately mirrored to it. A capture that shows no particular flow can indicate the wrong interface, an incorrect filter, or a visibility boundary—not proof that the network never sent the packets. That distinction matters in incident analysis, where a negative observation can otherwise be exaggerated into a conclusion.

Begin with a known-good PCAP captured in an approved lab. A file is deterministic: each replay yields the same packets, and it avoids accidental collection of credentials or personal data. Move to a live interface only when the investigation actually needs live timing or environmental differences. Keep the source file immutable, record its hash, and store working notes separately.

Understand what threads do and do not improve

sniff() is a synchronous call: it normally returns after a stopping condition such as a packet count or timeout. When a graphical interface or controller must remain responsive, the capture can run outside the main control path. That is a responsiveness decision, not a guarantee of greater packets-per-second throughput. Scapy’s own documentation explicitly warns that asynchronous sniffing does not necessarily improve performance and may make it worse. Multiple separate capture threads can duplicate work, increase synchronization overhead, and complicate shutdown.

Scapy offers AsyncSniffer, which wraps asynchronous capture with a small lifecycle API: start(), stop(), and join(). For an application whose real need is to continue updating its interface while monitoring packets, that API is usually clearer than manually launching an arbitrary threading.Thread around a blocking function. It accepts the core sniff() parameters, including iface, filter, count, timeout, prn, and store. The relevant Python thread still matters, but Scapy owns the capture-side controls.

The running flag indicates lifecycle state; it is not a measure of packet loss. results contains stored packets only if storing was enabled. In a long-running diagnostic, deliberately retaining every packet can exhaust memory. Choose whether the investigation needs complete packet data, limited header summaries, or just counters before starting capture.

Use an explicit start–stop lifecycle

For a bounded, approved test capture, the following pattern separates a controller from the capture activity. Replace the interface name with one owned by the lab and confirm its existence on that host. A short timeout keeps the example finite even if the operator forgets to request a stop.

from scapy.all import AsyncSniffer, IP

summaries = []

def observe(packet):
    if IP in packet and len(summaries) < 200:
        summaries.append((packet[IP].src, packet[IP].dst))

sniffer = AsyncSniffer(
    iface="lab0", filter="ip", prn=observe,
    store=False, timeout=20
)
sniffer.start()
# The controlling application can do other work here.
sniffer.join()          # Waits for this finite timeout or packet completion.
print(len(summaries))

This sample uses join() without an explicit stop() because timeout already bounds the capture. For a user-controlled live session, call stop() after the operator’s stop request while the capture is running; it normally joins the capture and returns its stored packets when store=True. Do not blindly call stop() on a completed sniffer or assume it is safe to stop an instance that never started. Place lifecycle state changes behind one controller rather than several competing buttons or callbacks.

There is an important concurrency detail: the list in this tiny illustration is just a finite demonstration, not a general-purpose multiworker message channel. A production tool should avoid updating a GUI directly from packet callbacks. Use a bounded queue or an application-specific dispatcher for transfer to other threads, and keep callback work short. That design is treated separately in the article on thread-based analysis.

Filters are part of the evidence plan

Scapy accepts a Berkeley Packet Filter expression through filter= on supported capture backends. A BPF expression such as udp port 53 narrows collection to the DNS transport of interest. It does not say which packets will be useful after inspection; it determines which ones become observable in the capture. If the filter excludes TCP-based DNS or encrypted resolvers, a DNS troubleshooting conclusion must acknowledge that limitation. The same caution applies to tcp port 443: it includes TLS-encrypted connections, but generally not their application plaintext.

Capture filters are different from a Python lfilter, which evaluates packet objects after capture. The former can reduce the number of packets delivered to Scapy and protect resources under load; the latter may be useful for a complex predicate but cannot prevent the lower-level capture work. Scapy’s documentation recommends BPF filtering for efficiency. Use the smallest valid filter consistent with the question, and record the expression alongside the PCAP or summary report.

Before investigating a supposed failure, do a sanity check. Capture a deliberately generated, approved lab packet that should match the filter, then a packet that should not. Confirm the first appears and the second does not. Also check the correct interface, account privileges, capture backend, and whether a firewall or virtual switch makes the traffic visible there. A filter that excludes the relevant packet cannot support a claim that the remote system is silent.

Stopping conditions and blocking behavior are different

A count limit stops after the configured number of packets; a timeout stops after elapsed capture time; a stop_filter evaluates each received packet. These are not equivalent. In particular, stop_filter generally needs another packet to arrive before the callback can discover that a stop was requested. On a quiet network, a thread waiting for a packet may therefore remain blocked even after a Boolean flag is set. Avoid describing stop_filter as an immediate, unconditional remote stop mechanism.

Prefer Scapy’s documented AsyncSniffer.stop() when implementing interactive capture controls, and still set a finite timeout as a safety boundary for examples or scheduled diagnostics. join() waits for the capture thread to finish; it does not itself ask a never-ending capture to stop. Never assume a call to join() will release a thread that has neither timeout nor stopping condition. When building a long-lived monitoring service, test the shutdown behavior both during heavy traffic and during a completely idle interval.

If the capture is part of a service, define what happens when the capture backend fails to initialize, the named interface disappears, or the user cancels the operation. Report those states distinctly from an empty but successful capture. A canceled run may have useful partial observations, but its outcome must not be labeled a complete measurement. A monitoring controller should record start and end times, the reason for exit, and whether its summary is partial.

Limit retention before the run begins

The default convenience behavior of retaining captured packets is risky for longer captures. With store=False, the callback can inspect or summarize a packet without accumulating an unbounded PacketList. A finite count is reasonable for a classroom experiment; in an operational investigation, a time limit and bounded output can be more useful because an unexpectedly busy interface should not exhaust available resources. If complete packet evidence is needed, write a PCAP under the organization’s approved retention rules instead of silently keeping every object in RAM.

Packet payloads may include usernames, device identifiers, cookies, confidential application traffic, or other sensitive information even on an apparently routine network. Metadata also discloses hosts, addresses, and communication patterns. Decide whether the question truly needs payload inspection. Where a header-level view is sufficient, avoid printing raw payloads to terminals, application logs, or screenshots. Apply access control, retention limits, and redaction to exported summaries. Label synthetic lab output clearly so it is not confused with production incident evidence.

If analysis is performed after capture, keep two artifacts: the original controlled capture and a derived summary with timestamps, filter, tool/version information, and normalization assumptions. Derived charts should not become the only record of the event, because later review may need to check for parse errors or missing packets.

Diagnose apparent performance problems carefully

A capture that misses packets can have several causes: driver or kernel capture-buffer limits, insufficient permissions, callback processing that is too expensive, too-broad filters, high traffic, or the location of the capture point. Creating more Python threads does not repair each of these mechanisms. First simplify the callback, disable in-memory storage when appropriate, add a narrow filter, and run an approved baseline with known traffic. Compare measured outcomes rather than assuming the application is faster because the main loop remains responsive.

When throughput matters, distinguish acquisition from decoding, aggregation, and visualization. A GUI redraw for every packet can overwhelm the user interface without providing more useful diagnostics. Sampling a bounded summary of counts per short interval can preserve trends while reducing rendering work. Scapy is intentionally flexible for protocol experiments, not a substitute for a specialized high-throughput capture engine in every workload.

Document what the monitoring configuration cannot see. If the interface captures only one host’s traffic, it cannot establish the behavior of an entire VLAN. If only IP is filtered, non-IP link-layer events disappear. If encrypted traffic is counted, it usually should not be treated as observed HTTP content. These limits are part of technically honest reporting.

A repeatable shutdown and reporting test

A useful verification run has four stages. First, replay an approved PCAP and confirm expected protocol counts against a known reference. Second, start a short live capture on an isolated lab interface and verify filter matching. Third, request stop while packets are arriving and confirm that the controller stops exactly one running capture. Fourth, repeat the stop test during idle traffic and observe whether the application still terminates within the declared timeout. The fourth test is often the one an optimistic threading example misses.

Record the interface, capture and processing filters, tool version, exit reason, number of summaries produced, and whether a captured-packet count was available. If a test exits because of a timeout rather than a packet count, report that accurately. If a callback throws an exception, preserve the error and explain whether the output remains usable; never convert failure into a zero-packet success. These habits turn a scripting exercise into defensible evidence.

A reliable Scapy capture is not defined by the number of threads created. It is defined by explicit scope, observable state, bounded collection, predictable shutdown, and an output another analyst can reproduce. When those properties hold, threaded capture becomes a useful part of network troubleshooting rather than an uncontrolled background process.

img