Join our Newsletter — 33% off our NHI Course
Home› Guides› tcpdump and BPF Filters: Capturing Exactly the Traffic…
Guide Network Security

tcpdump and BPF Filters: Capturing Exactly the Traffic an Investigation Needs

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 15 min read
On this page

An unfiltered capture on a busy link fills disks in minutes, drops packets under load and sweeps up far more personal data than an investigation can justify. tcpdump, with a well written Berkeley Packet Filter (BPF) expression, lets an analyst collect only the hosts, ports and packet types a question needs, in files that can be rotated, hashed and handed over as evidence. This guide is for SOC and incident response analysts who already know where to capture and now need to capture precisely. It covers the tcpdump options that matter for investigations, the pcap-filter syntax, a recipe table by investigation need, ring buffers, and evidence handling. For where to place sensors and how much to keep, see the Network Monitoring and Packet Capture Guide.

Key takeaways

  • Filter in the kernel, not afterwards. A BPF expression is compiled and applied before packets are copied to tcpdump, so a tight filter cuts drops, disk use and the volume of unrelated personal data you hold.
  • Test every filter before it matters. Run it with -d to see the compiled code and against a saved capture with -r, so a typo does not silently capture nothing during an incident.
  • Know the IPv6 blind spots. The tcp[], udp[] and icmp[] byte accessors do not match IPv6 packets, so flag-based filters written for IPv4 miss IPv6 traffic entirely.
  • Rotate and bound every long capture. -C with -W builds a size-capped ring, -G rotates by time, and -z runs a command such as a hashing script on each closed file.
  • Treat captures as evidence and as personal data. Hash each file when it closes, record who captured what and why, restrict access, and confirm your authority to capture before you start.

Why targeted capture matters

Full packet capture answers questions nothing else can: exactly which bytes left a host, what a command and control channel looked like, whether a credential crossed the wire in clear text. It is also the most expensive and intrusive evidence source, so targeted capture is what an analyst runs on a sensor or affected server once a lead exists.

  • Capacity: the kernel capture buffer and the disk are finite. The tcpdump manual warns that larger snapshot lengths increase processing time and effectively reduce packet buffering, which can cause packet loss. A filter that discards 95% of traffic before it reaches user space is the cheapest performance fix available.
  • Analysis speed: a small capture of one host is quick to search; a capture of a whole segment is not. See the Wireshark for Security Analysis Guide.
  • Proportionality: every packet kept may hold personal data or credentials, so a tight filter is also data minimisation. See the Data Minimisation guide.
  • Attacker use of the same tools: ATT&CK T1040 Network Sniffing covers adversaries capturing traffic for credentials. An unexpected tcpdump process or a stray pcap file on a server is a detection lead, so log your own authorised captures.

tcpdump essentials

tcpdump is maintained by The Tcpdump Group alongside the libpcap library that compiles and applies filters. As checked in November 2026, the current stable releases listed on tcpdump.org are tcpdump 4.99.7 and libpcap 1.11.1, and the project page notes security fixes in recent libpcap releases, so keep sensor packages patched. The options below are the ones investigations depend on; all are described in the tcpdump manual page.

OptionWhat it doesWhy it matters in an investigation
-i interfaceSelects the capture interfaceName it explicitly; without it tcpdump picks the lowest numbered configured interface, which may be the wrong one
-w fileWrites raw packets to a file instead of printingAlways write to file for evidence; decode later with -r or Wireshark
-r fileReads a saved pcap or pcapng fileRe-filter an existing capture without touching the network
-nDoes not convert addresses and ports to namesStops tcpdump generating its own DNS lookups during capture and keeps raw values
-s snaplenBytes kept per packet; default 262144, and 0 also means the defaultReduce only to the smallest size that still holds the headers you need, for example when payload is out of scope
-B buffer_sizeOperating system capture buffer, in KiBRaise it on busy links to absorb bursts before packets are dropped
-Q in|out|inoutCaptures one direction only, where the platform supports itIsolates outbound traffic during exfiltration checks
-UPacket-buffered output when writing with -wEach packet reaches the file as received, so a crash or kill loses little
-Z userDrops root privileges after opening the device, before writing filesLimits the damage if a protocol dissector or parser bug is exploited
-F fileReads the filter expression from a fileVersion-controlled, reviewable filters; a command line expression is then ignored
-dPrints the compiled packet-matching code and stopsConfirms a filter compiles and shows how complex it is

Quote the filter in single quotes so the shell leaves parentheses and exclamation marks alone. When tcpdump stops it reports packets captured, received by filter and dropped by the kernel: record those numbers, because drops mean the capture is incomplete.

BPF filter syntax

tcpdump filters use the pcap-filter language, which libpcap compiles into BPF code. An expression is built from primitives, and a primitive is usually an identifier preceded by up to three qualifiers: a protocol (proto), a direction (dir) and a type. Where more than one is present, the protocol comes first and the type last, as in tcp dst port 443. If no direction is given, "src or dst" is assumed; if no type is given, host is assumed.

ElementValuesExampleNotes from the pcap-filter manual
Type qualifierhost, net, port, portrange, proto, protochain, gatewaynet 10.20.0.0/16CIDR form works for IPv4 and IPv6; a plain IPv6 net without a length is a host match
Direction qualifiersrc, dst, src or dst, src and dstsrc host 10.1.2.3802.11 adds ra, ta and addr1 to addr4
Protocol qualifierether, ip, ip6, arp, tcp, udp, sctp and othersudp port 53Without it, port 53 means TCP, UDP or SCTP port 53
Special primitivesbroadcast, multicast, inbound, outbound, vlan, mpls, vxlan, geneve, less, greatergreater 1200The first vlan, mpls, vxlan or geneve keyword shifts decoding offsets for the rest of the expression
Logical operatorsand (&&), or (||), not (!)host 10.1.2.3 and not port 22not binds tightest; and and or have equal precedence and associate left to right, so use parentheses
Byte accessorproto[offset:size], size 1, 2 or 4ip[6:2] & 0x1fff = 0tcp[], udp[] and icmp[] accessors do not match IPv6 packets
Named fields and valuestcpflags, icmptype, icmp6type; tcp-syn, tcp-ack, tcp-rst, tcp-fin, icmp-echotcp[tcpflags] & tcp-rst != 0Readable alternatives to raw offsets and bit masks
Relations>, <, >=, <=, =, !=, with + - * / & | << >>len >= 1000All values are 32-bit unsigned integers

Traps that make filters silently wrong

  • Implicit keywords: an identifier without a keyword reuses the most recent one. The manual's example: not host vs and ace means not host vs and host ace, not not (host vs and host ace).
  • IPv6: tcp[tcpflags] filters only see IPv4. The port primitive also has limits: for IPv4 it implies the first fragment or an unfragmented packet, and for IPv6 it implies no extension headers. On dual-stack networks, check whether the suspect traffic uses IPv6 before trusting a flag filter.
  • Encapsulation: on trunk or overlay links, host 10.1.2.3 will not match VLAN-tagged or VXLAN-wrapped packets unless the expression includes the vlan or vxlan keyword. Put host 10.1.2.3 or before vlan and host 10.1.2.3 if untagged traffic is also present, because vlan shifts later offsets.

Filter recipes for investigations

Addresses below use documentation ranges (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24) and private ranges; substitute your own.

Investigation needFilter expressionNotes
Everything to and from one suspect host, minus your own SSH sessionhost 10.1.2.3 and not (tcp port 22 and host 10.9.9.9)10.9.9.9 is the analyst workstation; keeps the capture clean of your own commands
Traffic between a host and a known bad addresshost 10.1.2.3 and host 203.0.113.50Narrowest beacon capture; pair with the Beaconing and C2 Detection Guide
DNS sent to resolvers other than the approved onesport 53 and not host 10.0.0.53 and not host 10.0.0.54Finds hard-coded resolvers and possible DNS tunnelling (T1071.004); DNS over HTTPS will not appear
Outbound connection attempts (IPv4 SYN without ACK)tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-synOne packet per attempt, so it stays small; useful for scanning (T1046) and new-peer checks
Uploads from an internal range to the internetsrc net 10.20.0.0/16 and not dst net 10.0.0.0/8 and greater 1000Large outbound packets only; a starting point for exfiltration checks (T1048)
Clear-text protocols that may carry credentialstcp port 21 or tcp port 23 or tcp port 110 or tcp port 143 or tcp port 389FTP, Telnet, POP3, IMAP and LDAP without TLS; handle the output as secret material
SMB and RPC lateral movement between two subnetssrc net 10.30.0.0/24 and dst net 10.40.0.0/24 and (tcp port 445 or tcp port 135)See the Lateral Movement Guide
Possible tunnelling over ICMPicmp[icmptype] == icmp-echo and greater 200Echo requests larger than usual ping sizes (T1572); IPv4 only, use icmp6 for IPv6
Tagged traffic for one host on a trunkvlan 120 and host 10.1.2.3Offsets shift after vlan, so keep it first
Headers only, payload out of scopeAny filter above, with -s 128Enough for most Ethernet, IP and TCP headers; check truncation markers before relying on it

Build filters from the outside in: host or subnet first, then ports and flags, testing with -d and -r at each step. For high-volume parsing of metadata rather than packets, the Zeek Network Monitoring Guide covers the better tool.

Capture handling: rotation, size and evidence

An investigation capture often runs for hours or days. tcpdump has three options that bound it, and the manual describes their interaction precisely.

OptionBehaviourUse it for
-C file_sizeOpens a new file when the current one exceeds the size; the default unit is millions of bytes, and k, m or g suffixes switch to KiB, MiB or GiB. Later files take the -w name plus a numberKeeping each file small enough to copy, hash and open
-W filecount with -CLimits the number of files and starts overwriting from the first, creating a rotating buffer; file names are zero-padded so they sortA fixed disk budget, for example -C 500 -W 100 for roughly 50 GB
-G secondsRotates the -w file every interval; the -w name should contain a strftime time format, or each new file overwrites the previous oneHourly files that line up with log searches, for example -w /cap/host-%Y%m%d-%H%M.pcap -G 3600
-W filecount with -GLimits the number of rotated files and exits when the limit is reachedA capture that must stop after a set period, for example -G 3600 -W 24 for a day
-z commandRuns the command with the closed file's name after each rotation, at low priority, in parallel to the capture; not available on WindowsHashing, compressing or moving each completed file

The manual notes that when -C and -G are combined, -W is ignored except for file naming, so do not rely on it as a ring in that mode. A ring buffer also overwrites evidence: once an incident is confirmed, copy the relevant files out of the ring immediately or stop the capture.

Hashing and evidence handling

  1. Record the authority and scope first: case reference, who approved the capture, the sensor, interface, filter text (keep the -F file) and start time in UTC.
  2. Hash each file when it closes: point -z at a small script that writes the SHA-256 of the closed file to a separate manifest before any compression. Hash the original file, then compress a copy if needed, so the recorded hash always refers to the captured bytes.
  3. Capture the drop counters: save tcpdump's end-of-capture statistics with the files.
  4. Verify on transfer: recompute the hash after copying to the evidence store. capinfos -H prints a file's SHA-256 (the Wireshark manual notes its SHA-1 output may be removed), and capinfos -a, -e and -c give first and last packet times and packet count for the case notes.
  5. Work on copies: slice copies with editcap -A and -B and hash derived files as new exhibits.
  6. Protect and expire: store captures encrypted with access limited to the case team, and delete them at the end of the retention period set for the case.

NIST SP 800-61 Rev. 3 maps incident response to CSF 2.0, where RS.AN-07 calls for incident data and metadata to be collected with integrity and provenance preserved. The steps above are how a packet capture meets that outcome. For forms and custody records, see the Evidence Handling and Chain of Custody Guide and the Chain of Custody Form Template. The pcapng format, which can carry per-packet comments and hashes (the epb_hash option), is still an IETF Internet-Draft (draft-ietf-opsawg-pcapng-06, intended Informational, checked November 2026), so treat its options as convenient rather than as your evidence record.

On production hosts: never run -w without a -W limit, write to a dedicated partition outside web roots and shared temp directories, remove files from the host after transfer, and log the capture as an incident action so monitoring teams do not treat it as T1040 activity.

Packet captures can contain message content, credentials, health or financial data and communications of people who are not under investigation. The legal basis to capture varies by jurisdiction and by whose traffic it is: interception and communications privacy laws, employment law and data protection law can all apply, and authority for your own corporate network differs from authority for a customer's or a provider's network. NIST SP 800-86 advises applying its forensic practices only after consulting management and legal counsel about the laws that apply. This section is general guidance and not legal advice.

  • Purpose and approval: capture under a documented incident or monitoring purpose with named approval.
  • Minimise: filter to the hosts and protocols in scope, reduce snaplen when payload is not needed, and keep the capture window as short as the question allows.
  • Workforce monitoring: where staff traffic is captured, follow your monitoring policy and any required data protection impact assessment. In the UK, the ICO's monitoring workers guidance applies and was marked as under review in 2026 following the Data (Use and Access) Act. See the Employee Monitoring and Privacy Guide and the DPIA Template.
  • Third parties: never capture on networks you do not operate without the operator's written authority.

Framework mapping

FrameworkReferenceHow targeted capture supports it
NIST CSF 2.0DE.CM-01, DE.AE-02Network monitoring and analysis of adverse events
NIST CSF 2.0RS.AN-03, RS.AN-07Establishing what happened, with integrity and provenance of incident data preserved
NIST SP 800-53 Rev. 5SI-4, AU-9, AU-11System monitoring, protection of captured records, and retention
ISO/IEC 27001:2022 Annex AA.8.16 Monitoring activitiesMonitoring networks for anomalous behaviour
MITRE ATT&CK v20T1040, T1046, T1048, T1071.004, T1572Adversary sniffing to detect, and techniques the recipes help investigate

Useful measures for a capture capability: the share of incident captures with zero kernel drops, the median time from request to first packet on disk, the share of evidence files with a recorded hash and custody entry, and the number of captures past their retention date (target zero).

Practitioner checklist

  • Confirm authority, scope and approver for the capture and record them in the case.
  • Name the interface with -i, use -n, and drop privileges with -Z.
  • Write the filter in a version-controlled -F file, quoted, using literal addresses.
  • Check the filter with -d and against a sample with -r before the real capture.
  • Account for IPv6, VLAN and overlay encapsulation in the expression.
  • Bound every long capture with -C and -W or -G and -W on a dedicated partition.
  • Hash each closed file with a -z script and record the drop counters.
  • Verify hashes on transfer, work only on copies, and log custody.
  • Encrypt stored captures, restrict access and delete them on schedule.

Standards and references

Related NHI Mgmt Group resources: Network Monitoring and Packet Capture Guide · Wireshark for Security Analysis Guide · Zeek Network Monitoring Guide · EDR Telemetry vs Full Packet Capture · Incident Response Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.