tcpdump commands

tcpdump options and pcap filter expressions from the project's own manual pages for the stable releases tcpdump 4.99.7 and libpcap 1.10.7, grouped by task. Options are bare flags; rows that begin with tcpdump are whole command lines from the manual. Quote any filter that contains parentheses or an ampersand. Three options found only in the 5.0 development manual are marked as such; 802.11, ATM, IS-IS and DECnet filter primitives are left out.

141 commands in 15 sections. Checked row by row against tcpdump(1) manual page for tcpdump 4.99.7, plain-text edition (The Tcpdump Group, tcpdump.org) on . Edited by Jay.

Choosing an interface 10

Capturing from an interface may need special privileges; reading a saved capture file does not.

CommandWhat it does
-DList capture interfacesLong form --list-interfaces; prints a number and a name for each device, and either one can be passed to -i.
-i INTERFACECapture on one interfaceLong form --interface=INTERFACE; without it tcpdump picks the lowest-numbered interface that is up, loopback excluded.
-i anyCapture on all interfacesA pseudo-interface on Linux and on recent macOS and Solaris; captures on it are not made in promiscuous mode.
-IEnable monitor modeLong form --monitor-mode; limited to IEEE 802.11 Wi-Fi adapters on some systems, and the adapter may drop off its network.
-pLeave promiscuous mode offLong form --no-promiscuous-mode; the interface may still be promiscuous for another reason, so it does not replace an address filter.
-Q DIRECTIONCapture one direction onlyLong form --direction=DIRECTION; takes in, out or inout, and some platforms do not support it.
-LList data link typesLong form --list-data-link-types; prints the link types the interface offers in its current mode, then exits.
-y DATALINKTYPESet data link typeLong form --linktype=DATALINKTYPE; pick a value from the -L list, for capturing or for dumping filter code with -d.
-B BUFFER_SIZESet capture buffer sizeLong form --buffer-size=BUFFER_SIZE; the value sizes the operating system capture buffer in KiB.
--immediate-modeDeliver packets immediatelyPackets reach tcpdump as they arrive instead of waiting in a buffer; already the default when printing to a terminal.

Limiting and saving a capture 16

The -C size counts millions of bytes (1,000,000), not mebibytes; a k, m or g suffix switches to 1,024-based units.

CommandWhat it does
-c COUNTStop after a packet countEnds the capture once that many packets have arrived; without it tcpdump runs until it is interrupted.
--skip COUNTSkip the first packetsFrom the 5.0 development manual, absent in 4.99.7; with -c the count starts after the skipped packets.
-s SNAPLENLimit bytes kept per packetLong form --snapshot-length=SNAPLEN; the default is 262144 bytes, and a value of 0 selects that default.
-w FILEWrite packets to a fileSaves raw packets instead of decoding them on screen; tcpdump adds no extension, so name the file with .pcap yourself.
-w -Write packets to standard outputThe stream is buffered unless -U is added, so a program reading the pipe may see packets late.
-C FILE_SIZERotate savefile by sizeStarts a new numbered file once the size is passed; the unit is millions of bytes unless suffixed k, m or g.
-G ROTATE_SECONDSRotate savefile by timePut a strftime time format in the -w name; otherwise every new file replaces the one before it.
-W FILECOUNTLimit number of savefilesWith -C the files are reused in rotation as a ring buffer; with -G tcpdump exits after that many files.
-z POSTROTATE-COMMANDRun command after rotationRuns the command on each savefile closed by -C or -G rotation, for example gzip or bzip2 to compress it.
-UFlush output per packetLong form --packet-buffered; with -w every packet goes to the file as soon as it is saved, not when the buffer fills.
--printPrint while savingShows decoded packets on screen although -w is also storing the raw capture.
--print-sampling=NTHPrint a sample of packetsOnly in the unreleased 5.0 manual; prints every NTH packet, leaves the rest undecoded and switches --print on.
-Z USERDrop root privilegesLong form --relinquish-privileges=USER; switches to that user and its primary group before any output savefile is opened.
-lLine-buffer standard outputLets you watch packets while the output is piped or redirected; -U buffers per packet instead of per line.
tcpdump -l | tee datWatch and save printed outputLine buffering lets tee show each line on screen while it also writes the text to the file dat.
tcpdump -l > dat & tail -f datFollow redirected outputRuns the capture in the background printing into dat, while tail follows the file as lines are added.

Reading capture files 4

CommandWhat it does
-r FILERead packets from a fileOpens a pcap or pcapng savefile instead of an interface; reading a saved file needs no special privileges.
-r -Read packets from standard input
-V FILERead a list of savefilesThe named file lists the capture files to read; - takes that list from standard input.
--countPrint only the packet countApplies when reading capture files; with a filter, only the matching packets are counted.

Output detail 12

The 4.99.7 manual lists one -n flag that covers both host addresses and port numbers; it has no separate entry for -nn.

CommandWhat it does
-vVerbose outputAdds fields such as TTL, identification, total length and IP options, and verifies IP and ICMP header checksums.
-vvMore verbose outputAlso prints extra fields from NFS replies and decodes SMB packets completely.
-vvvMost verbose outputPrints telnet SB ... SE options in full, and in hex too when combined with -X.
-qQuiet outputPrints less protocol information so that each line stays short.
-eShow link-level headerAdds the link-layer header to every line, which reveals MAC addresses on Ethernet and 802.11.
-nSkip name resolutionShows host addresses and port numbers as numbers rather than looking up names for them.
-NStrip domain from host namesPrints the short host name, for example nic rather than nic.ddn.mil.
-fNumeric foreign addressesPrints IPv4 addresses outside the capture interface's network as numbers; unreliable on the any pseudo-interface.
-#Number each packetLong form --number; the packet number appears at the start of every output line.
--lengthsPrint packet lengthsOnly in the 5.0 development manual; puts caplen (bytes captured) and len (bytes on the wire) at the start of each line.
-SAbsolute TCP sequence numbersLong form --absolute-tcp-sequence-numbers; without it tcpdump prints relative sequence numbers.
-gKeep IP header on one lineLong form --ip-oneline; in verbose mode it removes the line break that normally follows the IP header.

Printing packet contents 5

CommandWhat it does
-APrint payload as ASCIILeaves out the link-level header; ignored when a hex option such as -x or -X is also given.
-xPrint packet data in hexAdds a hex dump after the headers, leaving out the link-level header and stopping at the snapshot length.
-xxHex with link-level headerSame hex dump as -x, but the link-level header is included.
-XPrint data in hex and ASCIIShows hex and ASCII together without the link-level header; suited to examining unfamiliar protocols.
-XXHex and ASCII with link headerSame dump as -X, but starting at the link-level header.

Timestamps 10

CommandWhat it does
-tHide timestampsRemoves the time column from every output line.
-ttEpoch timestampsPrints seconds since 1 January 1970 UTC, with fractions of a second.
-tttTime since previous linePrints the delta between each line and the one before it, in microseconds by default.
-ttttDate and time timestampsPuts the date in front of the usual hours, minutes, seconds and fraction.
-tttttTime since first linePrints the delta between each line and the first one, in microseconds by default.
-j TSTAMP_TYPESet timestamp typeLong form --time-stamp-type=TSTAMP_TYPE; valid type names depend on the interface and are listed by -J.
-JList timestamp typesLong form --list-time-stamp-types; prints the types the interface supports and exits, or nothing if none can be set.
--time-stamp-precision=TSTAMP_PRECISIONSet timestamp precisionAccepts micro or nano; when reading a savefile, time stamps are converted to that precision for display.
--microMicrosecond timestampsShorthand for --time-stamp-precision=micro; truncates time stamps when the savefile was written with nanosecond precision.
--nanoNanosecond timestampsShorthand for --time-stamp-precision=nano; microsecond savefiles get trailing zeroes added.

Compiling and checking filters 5

CommandWhat it does
-dDump compiled filter codePrints the packet-matching program in readable form and exits without capturing.
-ddDump filter as C fragmentEmits the same compiled filter in a form that can be pasted into C source.
-dddDump filter as decimal numbersEmits the compiled filter as plain decimal numbers with a count in front.
-ODisable filter optimizerLong form --no-optimize; only worth using when you suspect an optimizer bug.
-F FILERead filter from a fileTakes the filter expression from the file and ignores any expression typed on the command line.

Decoding and other options 10

CommandWhat it does
-T TYPEForce a protocol decoderInterprets the packets the filter selects as the named type, such as domain, rtp, snmp, tftp or vxlan.
-KSkip checksum verificationLong form --dont-verify-checksums; avoids false bad-checksum flags on interfaces that compute checksums in hardware.
-E SPI@IPADDR ALGO:SECRETDecrypt IPsec ESP packetsFor debugging only, since the key is visible to other users; needs a build with cryptography enabled.
-M SECRETValidate TCP-MD5 digestsChecks the digests in segments carrying the TCP-MD5 option of RFC 2385 against the given key.
-m MODULELoad SMI MIB moduleReads MIB definitions from the file; repeat the option to load more than one module.
-bPrint BGP AS numbers as ASDOTWrites each AS number in ASDOT notation where tcpdump would otherwise use ASPLAIN.
-uShow raw NFS handles
-HDetect 802.11s mesh headers
-hShow helpLong form --help; prints the version strings of tcpdump and libpcap followed by a usage message.
--versionShow versionPrints the version strings of tcpdump and of the libpcap it uses, then exits.

Host and network filters 13

CommandWhat it does
host HOSTMatch a host either wayTrue when the IPv4 or IPv6 source or destination is that name or address; host is assumed when no type is given.
src host HOSTMatch source hostOnly packets sent from that name or address pass the filter.
dst host HOSTMatch destination hostOnly packets addressed to that name or address pass the filter.
ip host HOSTMatch IPv4 host onlyPrefixing a host test with ip, arp, rarp or ip6 restricts it to that protocol.
net NETMatch a network either wayTakes a name from the networks database or a number such as 192.168.1, whose form sets the netmask.
src net NETMatch source networkTrue when the source address belongs to that network.
dst net NETMatch destination networkTrue when the destination address belongs to that network.
net NETADDR/LENMatch network by prefix lengthWorks for IPv4 and IPv6, and can be prefixed with src or dst.
net NETADDR mask NETMASKMatch network by netmaskIPv4 only; accepts a src or dst qualifier in front.
gateway HOSTMatch traffic through a gatewayThe host must be a name that resolves to both an IP and an Ethernet address; unusable in IPv6-enabled setups.
ip broadcastMatch IPv4 broadcastsTests both broadcast conventions, zeroes and ones, using the interface netmask, so it fails on the Linux any interface.
ip multicastMatch IPv4 multicast
ip6 multicastMatch IPv6 multicast

Port and protocol filters 13

CommandWhat it does
port PORTMatch a port either wayTakes a number or an /etc/services name; a bare number matches TCP, UDP and SCTP alike.
src port PORTMatch source portLooks only at the port the packet was sent from.
dst port PORTMatch destination portWith a number only the port is checked, so dst port 513 shows both TCP login and UDP who traffic.
portrange 6000-6008Match a range of portsBoth ends are inclusive, and src or dst in front limits the direction.
tcp src port PORTMatch TCP source port onlyAny port or portrange test can be prefixed with tcp, udp or sctp to pin the protocol.
udp portrange 7000-7009Match a UDP port rangeA proto qualifier in front of the range restricts the match to UDP.
tcpMatch TCP packetsAbbreviation for proto \tcp; udp, sctp, ah, esp and pim work the same way.
icmpMatch ICMP packetsAbbreviation for ip proto 1, so it covers IPv4 ICMP only.
icmp6Match ICMPv6 packetsStands for ip6 proto 58, the IPv6 counterpart of icmp.
ip proto PROTOCOLMatch IPv4 by protocolTakes a number or a name such as icmp, tcp or udp; names that are keywords must be escaped with a backslash.
ip6 proto PROTOCOLMatch IPv6 by protocolDoes not follow the IPv6 extension header chain; ip6 protochain exists for that.
proto PROTOCOLMatch IPv4 or IPv6 by protocolCovers both IP versions in one test, without following the header chain.
ip6 protochain 6Match TCP anywhere in IPv6 chainFinds a TCP header behind extension headers, but cannot run in the kernel filter, so it can be slow.

Length and byte offset filters 6

CommandWhat it does
less LENGTHMatch packets up to a lengthTrue when the packet is no longer than the value; the same test as len <= length.
greater LENGTHMatch packets of a minimum lengthTrue when the packet is at least that long; the same test as len >= length.
PROTO [ EXPR : SIZE ]Read bytes from a headerGives SIZE bytes (1, 2 or 4, default 1) at offset EXPR of the named protocol layer.
ether[0] & 1 != 0Match all multicast framesTests the lowest bit of the first byte of the link-layer header.
ip[0] & 0xf != 5Match IPv4 packets with options
ip[6:2] & 0x1fff = 0Match unfragmented or first fragmentPasses whole IPv4 datagrams and fragment zero; tcp and udp index operations apply this check by themselves.

TCP flag filters 6

Byte-offset tests on transport headers, such as tcp[13] and tcp[tcpflags], only look at IPv4 packets and never match IPv6.

CommandWhat it does
tcp[tcpflags]Read the TCP flags byteNamed form of tcp[13]; test it against tcp-syn, tcp-ack, tcp-fin, tcp-rst, tcp-push, tcp-urg, tcp-ece or tcp-cwr.
tcpdump -i xl0 'tcp[13] == 2'Capture SYN-only packetsByte 13 of the TCP header equals 2 only when SYN is the single flag set.
tcpdump -i xl0 'tcp[13] & 2 == 2'Capture any packet with SYN setMasking with 2 keeps only the SYN bit, so SYN-ACK packets match as well.
tcpdump -i xl0 'tcp[tcpflags] & tcp-push != 0'Capture packets with PSH setUses flag names instead of numbers; quote the expression so the shell does not interpret the & character.
tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net localnet'Capture SYN and FIN packetsPrints where TCP conversations with non-local hosts begin and end.
tcpdump 'tcp[tcpflags] & (tcp-rst|tcp-ack) == (tcp-rst|tcp-ack)'Capture RST-ACK packetsMasks the flags byte down to RST and ACK, then requires both bits to be on.

Combining filters 9

CommandWhat it does
andRequire both conditionsCan also be written &&; it has the same precedence as or and groups left to right.
orAccept either conditionCan also be written ||; it is evaluated left to right together with and.
notNegate a conditionCan also be written !; it binds more tightly than the other two operators.
host foo and not port ftp and not port ftp-dataExclude ports from a host matchKeeps traffic for host foo while leaving out the FTP control and data ports.
tcp dst port ftp or ftp-data or domainReuse qualifiers across a listIdentical qualifiers may be dropped, so each later name is still read as a TCP destination port.
not host vs and aceNegate only the first hostThe missing keyword is filled in as host ace; it does not mean neither vs nor ace.
not (host vs or ace)Exclude several hostsParentheses group the alternatives so the negation covers both hosts.
tcpdump host helios and \( hot or ace \)Group hosts with escaped parenthesesBackslashes keep the shell from interpreting the parentheses around the two alternatives.
tcpdump 'gateway snup and (port ftp or ftp-data)'Quote an expression for the shellSingle quotes protect the parentheses from the shell; this one prints FTP traffic passing gateway snup.

Examples from the manual 9

CommandWhat it does
tcpdump host sundownPrint traffic of one hostShows every packet going to or coming from the host named sundown.
tcpdump ip host ace and not heliosPrint host traffic except one peerShows the IP traffic that ace exchanges with any machine other than helios.
tcpdump net ucb-etherPrint traffic of one networkThe network is given by name, selecting whatever local machines exchange with hosts at Berkeley.
tcpdump ip and not net localnetPrint non-local IP trafficSelects IP packets whose source and destination both lie outside the network named localnet.
tcpdump 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'Print HTTP packets carrying dataIPv4 only; subtracts the IP and TCP header lengths from the total length to skip SYN, FIN and bare ACK packets.
tcpdump 'gateway snup and ip[2:2] > 576'Print large packets via a gatewayReads the two-byte IP length field and keeps packets above 576 bytes routed through snup.
tcpdump 'ether[0] & 1 = 0 and ip[16] >= 224'Print IP multicast in unicast framesMatches IP broadcast or multicast destinations carried in Ethernet frames addressed to a single station.
tcpdump 'icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply'Print ICMP except pingDrops echo requests and replies by testing the ICMP type field by name.
icmp6[icmp6type] != icmp6-echo and icmp6[icmp6type] != icmp6-echoreplySelect ICMPv6 except pingThe IPv6 counterpart of the ICMP filter above, given as a bare expression in the pcap-filter manual.

Notes

The capture you run first

sudo tcpdump -i eth0 -n port 443 is the shape of most captures: an interface, no name resolution, a filter. -i INTERFACE picks the interface (-i any captures all of them, though not in promiscuous mode), and -D lists what is available. -n stops tcpdump converting host addresses and port numbers to names; the manual documents that one flag for both and has no entry for -nn. Without it, a busy capture stalls on reverse lookups and the output changes shape. -c COUNT stops after a number of packets, which prevents an unbounded capture on a production host.

Writing files instead of reading the screen

-w FILE writes raw packets to a pcap file and prints nothing unless --print is added, and -r FILE reads one back with a filter applied, so a large capture can be sliced after the fact. For long captures, -C FILE_SIZE rotates files at a size in millions of bytes and -G ROTATE_SECONDS rotates on time. -W FILECOUNT caps how many files a size rotation keeps; with a time rotation it ends the capture after that many files. -s SNAPLEN limits how many bytes of each packet are saved; the default is 262144 bytes, and the manual advises the smallest value that still holds the protocol information you need.

Reading the output

-v, -vv and -vvv add protocol detail such as TTL, IP ID and checksum results. -A prints packet payloads as ASCII, which makes unencrypted HTTP readable, and -X prints hex and ASCII side by side. -e adds the link-level header with MAC addresses, needed for ARP and VLAN problems, and -tttt prints full timestamps with the date. -d dumps the compiled filter, which is how you check that a complicated expression means what you think.

Questions

Why is tcpdump slow to print anything?

It is resolving hostnames and service names. Add -n, which disables both lookups; the manual has no separate -nn. Output sent to a pipe or a file is also buffered: -l makes it line buffered.

How do I capture to a file for Wireshark?

tcpdump -i eth0 -w capture.pcap with a filter; type the .pcap extension yourself, because -w FILE does not add one. Open the file in Wireshark, or read it back with -r FILE.

How do I capture only the packet headers?

Use -s SNAPLEN with the smallest snapshot length that still holds the headers you need. The default is 262144 bytes, which keeps whole packets; packets cut short by the limit are marked [|proto] in the output.

How do I keep a long capture from filling the disk?

Combine -w FILE with -C FILE_SIZE (rotate by size) and -W FILECOUNT: the files are then overwritten in rotation. With -G ROTATE_SECONDS (rotate by seconds), -W ends the capture after that many files instead. -c COUNT stops after N packets.

Sources and checks

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.