00->1
Learning pathStep 59 of 62Detection, response and testing ← All writeups

Packet Capture and Port Scanning Basics, Explained

If you are reading this, you have probably seen Wireshark and Nmap in every security course and you want to know what they actually show you, how to read the output, and how to use them without breaking a rule.

By the end you will be able to read a line of tcpdump output, find the TCP handshake, an HTTP request and a DNS lookup in a real capture, write simple filters, know the difference between a capture filter and a display filter, explain what a port scan reports and what each port state means, and say when scanning is allowed. You will do this on a sample file, with no risk to anyone.

You should know what a packet, a port and a TCP handshake are. Computer and Networking Basics and Handshakes explain them.


1. Why look at packets?

Everything on a network is a stream of packets. Reading them lets you see what really happens, instead of what you were told happens:

  • A defender uses captures to investigate an incident, see what a suspicious machine talked to, or check whether data left the network unencrypted.
  • A learner uses captures to see protocols working: the handshake, a web request, a DNS lookup.
  • A tester uses scans to find which services a system exposes, because every open port is something an attacker can try.

The two jobs have different tools. Capture tools (tcpdump, Wireshark) record and display traffic. Scanners (Nmap) send probes to find out what is listening. Both come with a warning, covered in section 6: use them only where you are allowed to.


2. Two capture tools

Tool What it is Best for
tcpdump A command-line packet analyser. It prints one line per packet, or saves packets to a file Quick looks, servers without a screen, scripts
Wireshark A graphical analyser that breaks every packet into layers and lets you filter and search Studying a capture in depth

They work on the same capture files, in the pcap format, so you can capture with one and read with the other.

One point to know early: capturing live traffic needs special privileges on most systems. The tcpdump manual says reading a saved packet file "doesn't require special privileges", but capturing from a network interface does. That is why this post starts with a saved file.

Capture only what you may

A capture contains whatever crossed the wire, including passwords and messages if they were not encrypted. Capture your own traffic, or traffic on networks where you have permission. Do not capture on a shared or work network without authorization. Security Testing explains scope and permission.


3. Hands-on: read a real capture with tcpdump

The Wireshark project keeps a page of sample captures for learning (Wireshark: Sample Captures). One of them, http.cap, is a short capture of someone loading a web page. It is an old file, which is fine: the protocols have not changed.

Put it in its own empty folder, so that nothing else is mixed in, and download it from the Sample Captures page (look for http.cap in the list):

mkdir capture-lab && cd capture-lab
# save http.cap from the Wireshark Sample Captures page into this folder
file http.cap
# http.cap: pcap capture file, microsecond ts (little-endian) - version 2.4 (Ethernet, capture length 65535)
shasum -a 256 http.cap
# 25a72bdf10339f2c29916920c8b9501d294923108de8f29b19aba7cc001ab60d  http.cap

(If your hash is different, the file was changed or a newer version was uploaded; treat it with care, and the lines below may not match.)

Treat any capture file you download as untrusted data. Capture tools parse complicated formats, so keep tcpdump and Wireshark up to date, and do not open captures from strangers on a computer that holds important files.

The first four packets

tcpdump -nr http.cap -c 4

The flags: -n means do not turn addresses and ports into names, -r http.cap means read from the file, and -c 4 stops after four packets (tcpdump manual). Output (the addresses are the capture's own; the first line, written to the error stream, varies a little between tcpdump versions):

reading from file http.cap, link-type EN10MB (Ethernet)
15:47:07.311224 IP 145.254.160.237.3372 > 65.208.228.223.80: Flags [S], seq 951057939, win 8760, options [mss 1460,nop,nop,sackOK], length 0
15:47:08.222534 IP 65.208.228.223.80 > 145.254.160.237.3372: Flags [S.], seq 290218379, ack 951057940, win 5840, options [mss 1380,nop,nop,sackOK], length 0
15:47:08.222534 IP 145.254.160.237.3372 > 65.208.228.223.80: Flags [.], ack 1, win 9660, length 0
15:47:08.222534 IP 145.254.160.237.3372 > 65.208.228.223.80: Flags [P.], seq 1:480, ack 1, win 9660, length 479: HTTP: GET /download.html HTTP/1.1

How to read a line

The tcpdump manual gives the format of a TCP line: src > dst: Flags [tcpflags], seq ..., ack ..., win ..., options [...], length .... "Src and dst are the source and destination IP addresses and ports."

Part Meaning
15:47:07.311224 Time of day when the packet was seen
145.254.160.237.3372 > 65.208.228.223.80 Source address and port, then destination address and port. Port 80 is the web server (HTTP)
Flags [S] The TCP flags. The manual lists them: S (SYN), F (FIN), P (PUSH), R (RST), and . for ACK
seq, ack Sequence and acknowledgement numbers
win How much receive buffer space the sender has available
length Bytes of payload data in this packet

Spot the TCP three-way handshake

The first three lines are the handshake from Handshakes:

  1. Flags [S], seq 951057939 — the client (145.254.160.237) sends a SYN: "can we talk?".
  2. Flags [S.], seq 290218379, ack 951057940 — the server answers SYN-ACK (S.). Its ack is the client's number plus one (951057939 + 1 = 951057940), confirming it received the SYN.
  3. Flags [.], ack 1 — the client sends a plain ACK. The connection is open.

Why does the third line say ack 1 and not a large number? The tcpdump manual explains: the first time it sees a conversation it prints the real sequence numbers, and after that it prints numbers relative to the start ("relative byte positions in the conversation's data stream"). The ack number is the "sequence number of the next data expected" from the other side, so ack 1 means "the next byte I expect from you is the first byte of your data".

The fourth line has flags P. (PUSH and ACK) and length 479: the client now sends data. tcpdump decodes it for us: HTTP: GET /download.html HTTP/1.1. The client is asking the web server for the page /download.html. Because this is plain HTTP, the request is readable. That is exactly why HTTPS matters: on an unencrypted connection, anyone on the path can read this.

Show only what matters: filters

You can give tcpdump a filter expression at the end of the command. Try these:

tcpdump -nr http.cap 'udp port 53'
15:47:09.864896 IP 145.254.160.237.3009 > 145.253.2.203.53: 35+ A? pagead2.googlesyndication.com. (47)
15:47:10.225414 IP 145.253.2.203.53 > 145.254.160.237.3009: 35 4/0/0 CNAME pagead2.google.com., CNAME pagead.google.akadns.net., A 216.239.59.104, A 216.239.59.99 (146)

That is a DNS lookup. In the first line, 35 is the query ID, the + means the client asked the resolver to do the full lookup (the manual calls this the "recursion desired flag"), and A? asks for an address record for pagead2.googlesyndication.com. The resolver at port 53 answers with two aliases (CNAME records) and two addresses. You are looking at the process from Computer and Networking Basics, DNS section, on the wire. The query ID is the 16-bit value that DNS Poisoning shows attackers try to guess.

tcpdump -nr http.cap 'tcp[tcpflags] & tcp-syn != 0'

This keeps only packets with the SYN flag set, which gives lines 1 and 2 from above: the start of each TCP connection. The tcpdump manual describes this style of test for capturing "packets with particular flag combinations".

Other useful filters from the manual's syntax: host 65.208.228.223 (traffic to or from that address), src host ..., dst port 80, tcp, udp, and combinations with and, or, not.

Count who talked

You can also pipe the output into ordinary Linux tools (see Linux Fundamentals):

tcpdump -nr http.cap 2>/dev/null | awk '{print $3}' | sed 's/\.[0-9]*$//' | sort | uniq -c | sort -rn
  20 145.254.160.237
  18 65.208.228.223
   4 216.239.59.99
   1 145.253.2.203

The capture has 43 packets. Twenty were sent by the client and eighteen by the first web server, four by a second web server (the advertising address from the DNS answer) and one by the DNS resolver. In one pipeline you have summarised a conversation. This is the basic move of traffic analysis: who talked to whom, and how much.

Capturing your own live traffic

On your own computer, with privileges (on macOS and Linux that usually means sudo), the general forms are:

tcpdump -D                       # list capture interfaces
sudo tcpdump -i en0 -n -c 20     # print 20 packets from interface en0 (use a name from tcpdump -D)
sudo tcpdump -i en0 -w out.pcap  # write packets to a file, to open later in Wireshark

The manual describes -i as selecting the interface, -w file as writing the raw packets to a file that "can later be printed with the -r option", and -D as listing interfaces. Interface names differ between systems and computers (for example en0 on a Mac, often eth0 or wlan0 on Linux), so run tcpdump -D and use a name from your own list.


4. Wireshark

Open http.cap in Wireshark and you see the same 43 packets in a list. Click one and the lower panes show it layer by layer: Ethernet, IP, TCP, HTTP. This is the best way to learn what each field means.

Two kinds of filter

Wireshark has two filter systems, and beginners mix them up. They are different languages used at different times.

Capture filter Display filter
When Before and during capture After capture, on what you already have
Effect Packets that do not match are never recorded Packets that do not match are hidden, but still in the file
Syntax "Wireshark capture filters are written in libpcap filter language" (the same family tcpdump uses). Example from the Wireshark guide: tcp port 23 Wireshark's own display-filter language, which "enables you to precisely control which packets are displayed"
Example tcp port 80 http.request

(Wireshark User's Guide: capture filters and display filters.)

The tcpdump filters you used above are in the capture-filter style. The Wireshark guide's own examples of display filters:

  • tcp — "To only display TCP packets, type tcp into Wireshark's display filter toolbar."
  • http.request — "to only display HTTP requests".
  • ip.addr==192.168.0.1 — packets to or from that address.
  • tcp.port in {80, 443, 8080} — packets using any of those ports.

Try dns in the display filter for http.cap, then http.request, then ip.addr==216.239.59.99. Compare with the tcpdump results.

A practical tip: use a capture filter when you must limit what is recorded (for example, to save space or avoid capturing unrelated traffic). Use display filters when you are exploring a capture, because the hidden packets are still there if you change your mind.


5. Port scanning with Nmap

A port scan asks a computer, port by port, "is anything listening here?". Nmap is the standard tool. The question matters for defence as much as for offence: every open port is a service an attacker can probe, so knowing what you expose is the first step to reducing it. This ties directly to Reconnaissance, where attackers learn about a target before attacking.

The basic commands

nmap TARGET                      # scan the default 1,000 TCP ports
nmap -p 22,80,443 TARGET         # scan specific ports
nmap -p 1-1024 TARGET            # scan a range
nmap -sV -p 80 TARGET            # also try to identify the service and its version

Replace TARGET with a machine you own, such as 127.0.0.1 for your own computer, or a lab machine from Build a Safe Practice Lab. The Nmap book states that, by default, nmap <target> scans 1,000 TCP ports. The -p option takes "an arbitrary list of port numbers": a single port such as -p 22, a range separated by a hyphen, or a comma-separated list. The -sV option runs after another scan has found open ports and "interrogates those ports to determine more about what is actually running", such as the application and version (Nmap Reference Guide).

The result is a list of ports and their state. Output differs by system, so this post does not show a sample; learn to read the states.

The six port states

State Nmap's definition
open "An application is actively accepting TCP connections, UDP datagrams or SCTP associations on this port"
closed "A closed port is accessible (it receives and responds to Nmap probe packets), but there is no application listening on it"
filtered "Nmap cannot determine whether the port is open because packet filtering prevents its probes from reaching the port"
unfiltered "The unfiltered state means that a port is accessible, but Nmap is unable to determine whether it is open or closed"
open|filtered Nmap "is unable to determine whether a port is open or filtered"
closed|filtered Nmap "is unable to determine whether a port is closed or filtered"

(Nmap Reference Guide: Port Scanning Basics.)

Reading them as a beginner:

  • open is the one to examine: something is listening and can be talked to.
  • closed means the machine is reachable but nothing listens there.
  • filtered usually means a firewall is in the way (see Network Defence), so you cannot tell what is behind it.

An open port is not automatically a vulnerability. It is a service to understand: is it needed, patched, and properly protected? Threats and Vulnerabilities and Security Operations cover the next steps.

Do it yourself in Python first

You wrote a tiny scanner in Python Basics for Security: it tried to connect to ports on 127.0.0.1 and reported open or closed. That is the core idea behind Nmap's simplest scan. Nmap adds speed, many scan types, service identification and careful handling of the six states above.


6. When is scanning allowed?

This is the most important section. The Nmap book is direct: "When used improperly, Nmap can (in rare cases) get you sued, fired, expelled, jailed, or banned by your ISP", and "Port scanning without authorization is sometimes against the provider's acceptable use policy (AUP)." It adds that "the question of whether port scanning is legal does not have a simple answer", and its advice is to "always secure written authorization from the target network representatives before initiating any scanning" (Nmap: Legal Issues).

Practical rules:

  1. Scan your own machines and lab. 127.0.0.1 is your own computer. Your lab's internal network is yours.
  2. Everything else needs written permission from the owner, in scope and time, before you start.
  3. Know what is permitted on practice hosts. The Nmap project says: "For testing purposes, you have permission to scan the host scanme.nmap.org", but only for "scanning with Nmap and not testing exploits or denial of service attacks", and it asks you not to run more than about a dozen scans a day against that host. Read the page itself before you use it.
  4. Do not scan your school, workplace or neighbours "to practise". That is the situation the warnings above describe.
  5. Be careful on bug bounty programs. Their rules may restrict or ban scanning. Read the scope first (see Vulnerability Disclosure and Bug Bounty).

7. Practise

  1. Re-run the tcpdump commands above on http.cap. Write down, in your own words, what each of the 43 packets is doing.
  2. Find the packet that carries the HTTP response (HTTP/1.1 200 OK). What does the server's length tell you about how the page is sent?
  3. In Wireshark, apply http.request. How many requests are there, and to which hosts?
  4. Use the sample captures page to download a second capture that interests you (one at a time, in the same folder). Identify the protocols in it.
  5. Start a local web server (python3 -m http.server 8000 --bind 127.0.0.1), then capture lo0 or lo (the loopback interface) with tcpdump while you load http://127.0.0.1:8000/ in a browser. The loopback interface is lo0 on macOS and lo on Linux. Watch the handshake and the request appear. This keeps all the traffic on your own computer.
  6. With a lab machine as the target, run Nmap against it and compare the open ports with what you started.

8. Common mistakes

Mistake The facts
"I'll capture on any network to learn" Captures can contain other people's data. Capture your own traffic or where you have permission
"tcpdump filters and Wireshark display filters are the same" tcpdump and Wireshark's capture filters use libpcap syntax. Wireshark's display filters are a separate language
"A capture filter is the same as a display filter" A capture filter discards non-matching packets before they are recorded. A display filter only hides them
"Open means vulnerable" It means something is listening. Check what, and whether it is patched and needed
"Closed and filtered are the same" Closed means reachable with nothing listening. Filtered means something blocked the probes
"No open ports means safe" Other attack paths exist: web apps, phishing, stolen credentials
"I can scan scanme.nmap.org however I like" The permission is limited to scanning, not exploits or denial of service, and at a low rate
"It's only a scan, it can't hurt" The Nmap book says scanning can get you sued, fired, expelled, jailed or banned. Get written permission
"I'll open captures from the internet freely" Treat downloaded captures as untrusted input and use current tools
"Encrypted traffic shows nothing" You can still see who talked to whom, when and how much, even without contents. Contents are hidden

Closing

Packets are the ground truth of a network. tcpdump gives you quick, scriptable views, Wireshark gives you a layer-by-layer microscope, and Nmap tells you which doors are open. With a single old capture file you saw a TCP handshake, an HTTP request and a DNS lookup, which are the pieces behind almost every network attack in this series.

Keep these points:

  • tcpdump prints one line per packet. Read src > dst: Flags [..], seq, ack, win, length.
  • Flags: S is SYN, . is ACK, P is PUSH, F is FIN, R is RST. SYN, SYN-ACK, ACK is the handshake.
  • Sequence numbers are shown relative to the start of the conversation after the first packet.
  • Capture filters limit what is recorded; display filters hide what is shown. They are different languages.
  • Plain HTTP is readable on the wire. That is why encryption matters.
  • Nmap's states: open, closed, filtered, unfiltered, open|filtered, closed|filtered.
  • An open port is something to understand, not automatically a flaw.
  • Permission first. Scan your own systems, or get written authorization.

If you can read a capture, point to the handshake, the request and the DNS lookup, and explain what a scan result means and when you may run one, you have the foundation.

Related: Handshakes explains what you saw in the first three packets, Network Defence covers firewalls and intrusion detection that react to scans, and Reconnaissance shows scanning as part of an attacker's first steps.