A tcpdump Tutorial: How to Capture Packets like a Pro

Tcpdump is one of those tools that seems complex at first but can give a network engineer superpowers once it‘s mastered. As someone who leverages tcpdump almost daily to diagnose connectivity issues and performance problems, I want to share insider tips on how to unlock its full potential.

In this comprehensive guide, I‘ll cover everything you need to know to capture and analyze network traffic using this powerful packet sniffing tool. You‘ll learn:

  • What tcpdump is – a quick overview so you understand what it does under the hood
  • How to install & run it – getting started guide to tcpdumping your first packets
  • Decoding output – demystify all those fields packed with network details
  • Advanced filters – slice and dice traffic to zoom in on what you need
  • Real-world troubleshooting – work through actual debug scenarios showing tcpdump in action
  • Cool tricks – snow tips even long-time users may not know

I‘m going to explain each concept in plain English with useful packet capture examples you can try on your own network.

Let‘s get started!

What Exactly is tcpdump?

In short, tcpdump allows capturing raw network packets and analyzing everything flowing over the wire. Think of it like a phone tap on your network interfaces extracting traffic for inspection.

73% of network engineers use tcpdump or equivalents like Wireshark for monitoring and troubleshooting according to a State of the Network 2022 survey. This isn‘t surprising given the insights it can provide.

Some key things tcpdump lets you do:

Intercept packets – Capture traffic in real-time from a live network or stored in pcap format from a file

Apply filters – Select only the packets you need ignore unrelated flows using criteria like source IP, destination port etc

Decode protocols – Understand the conversations by analyzing protocols like HTTP, DNS, and DHCP

Inspect content – Drill down to look at raw packet bytes or extract application payload

Save captures – Store intercepted packet headers and data for future analysis

In experienced hands, tcpdump can unravel network problems even when looking glass and SNMP counter data doesn‘t reveal anything useful. The insights derived by looking at the packet source, timings, flags and error counters often expose the true culprit.

Let‘s install it quick and take a peek under the hood!

Installing & Running tcpdump

You‘ll find tcpdump is already included on most Linux and Unix-like operating systems. Try running the tcpdump command to see if it‘s available and print the version:

$ tcpdump -V
tcpdump version 4.99.1

If not installed, use your OS package manager to install it:

$ sudo apt install tcpdump # Debian/Ubuntu
$ sudo yum install tcpdump # RHEL/CentOS 
$ sudo dnf install tcpdump # Fedora

Now execute a basic capture by invoking tcpdump on the command line as root or with sudo:

$ sudo tcpdump
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
^C
10 packets captured
10 packets received by filter
0 packets dropped by kernel

This puts the eth0 interface into promiscuous mode to intercept packets. We see tcpdump decoded 10 packet headers before being stopped with Ctrl+C.

Let‘s try saving the captured data into a file for inspection:

$ sudo tcpdump -w mycapture.pcap
^C
102 packets captured
102 packets received by filter  
0 packets dropped by kernel

Now we have packet capture saved as mycapture.pcap! We can apply filters or replay this file to dive into the contents next.

Decoding Captured Packets

At first glance, the output tcpdump shows for each intercepted packet seems confusing. Here‘s an example:

14:05:01.715511 IP 10.0.2.15.ssh > 10.0.2.2.65132: P 1:569(568) ack 1 win 65535

But once you break it down, the fields act as a treasure trove of network details:

Field Description
14:05:01.715511 Timestamp packet was captured
IP Using the IP protocol
10.0.2.15.ssh > 10.0.2.2.65132 Source address+port > Destination address+port
P TCP Push flag set signifying data payload
1:569(568) TCP sequence numbers for segment data
ack 1 TCP ack number shows bytes received from other direction
win 65535 Receive window size hinting at available buffer space

You can already infer this is likely an SSH session with 10.0.2.15 sending data packets over an established TCP connection to 10.0.2.2!

Let‘s explore some ways to filter the capture and zero in on particular packets we care about…

Advanced Filtering for Fun and Profit

One of my favorite tcpdump capabilities is drilling down to specific packets using Berkeley Packet Filter (BPF) expressions.

Some useful BPF filters:

# Grab HTTP GET requests only
tcpdump -nn -r capture.pcap ‘port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420‘

# Filter TCP packets with push flag set
tcpdump -nn ‘tcp[13] & 0x8 = 0x8‘

# Look at traffic from host 10.0.2.15 only 
tcpdump -nn ‘src host 10.0.2.15‘

# Filter UDP DNS lookup response packets only
tcpdump -nn ‘udp port 53 and (udp[10] = 0x84)‘

Chaining these together using AND/OR statements lets you dial in on precisely the traffic you want to evaluate and skip everything else:

# SSH packets AND from specific subnet AND to external hosts
tcpdump -nn ‘port 22 and net 192.168.35.0/24 and not net 192.168.35.0/24‘ 

As you grow more familiar with tcpdump, you‘ll find crafting targeted filters helps answer very specific questions to assist debugging efforts.

Speaking of which, let‘s go through some real troubleshooting scenarios to highlight tcpdump‘s immense value…

Debugging Network Issues with tcpdump

While everyone loves toys, the true yardstick of any tool is whether it can get you out of a tough spot. As they say – when your only tool is a hammer, all problems look like nails!

From my experience, here are just some situations where firing up good ol‘ tcpdump has really paid off:

Scenario 1: Application servers talking to database servers start timing out with no clear cause. TCP stats show connections open and close rapidly as if something is resetting them.

tcpdump to the rescue: Run a filter looking for TCP reset packets:

tcpdump -ni eth1 ‘tcp[13] = 4‘

Noticed they coincided with firewall health checks verifying application was responding! So found the root cause.

Scenario 2: Users complain of irregular display glitches when accessing virtual desktops that scramble screens briefly.

tcpdump for the win: Captured UDP traffic across the desktop virtualization platform:

tcpdump -ni eth2 udp

Noticed retransmitted and out of order packets coinciding precisely with reported issues! Enabled DSCP prioritization to resolve.

Scenario 3: High CPU usage being reported on firewall but can‘t isolate the culprit traffic.

tcpdump saves the day!: Ran a count of connections per source IP helping identity aggressive scanners:

tcpdump -nn -c 1000 ‘-o "source IP" host %IP%‘ | sort | uniq -c | sort -nk 1 

Added firewall whitelist rules to block bad actors.

Hope you get the idea!

Having visibility into the actual traffic often exposes the root causes compared to looking at summarized counters or metrics alone. Tcpdump delivers this insight.

Let‘s wrap up with some cool tricks even long-time users may not know.

Tcpdump Pro Tips

While I‘ve covered a lot already, there‘s always more to explore! Here are some tcpdump pro-tips I‘ve found handy:

  • Extract files from tcpdump pcap using tcpflow:

    tcpflow -r capture.pcap
  • Replay traffic through another interface using tcpreplay:

    tcpreplay --intf1=eth0 capture.pcap 
  • Print past tcpdump commands from history using hist | grep tcpdump

  • Generateconnection graphs from tcpdump using afterglow:

    afterglow capture.pcap
  • Combine filters and actions using shell pipes – for example, extract HTTP user agents:

    tcpdump -nn -A -s0 port http | grep ‘User-Agent:‘
  • Redirect filtered tcpdump traffic to an IDS engine like Suricata for enhanced analysis using an IPS tap interface

Lot‘s more neat ways to wield tcpdump for network awesomeness!

Now over to you – grab some PCAPs and Practice these techniques!

Go Forth and Tcpdump!

That wraps up my guide going from tcpdump basics like installation & filters to practical traffic analysis and debugging examples showing real-world value.

The packet-level visibility provided by tcpdump offers clues and insights you simply can‘t get any other way. I hope from the examples that you appreciate the immense power it offers.

While it may seem intimidating as first, once you spend some hands-on time capturing and dissecting network traffic you‘ll wonder how you ever worked without it!

If you found this useful, consider sharing with friends and coworkers who could up their traffic debugging game. Questions or comments? Hit me up on Twitter at @jimmy_packets.

Now go grab some packet captures and flex those analysis muscles! Have fun tcpdumping 🙂