Knowledge

TCP and UDP

Updated 2026-11-06 · Present

Estimated time: 40 minutes.

Quick summary

Step 1 — Open a TCP listener with nc

Understand port binding in practice — nc creates a process listening on port 9000. With no process listening, a TCP SYN immediately gets an RST (connection refused). This is the foundation for debugging 'connection refused'.

RFC 9293 §3.5.2 specifies that when a TCP SYN arrives at a closed port (no process listening), the kernel immediately sends an RST — this is 'Connection refused'. nc -l creates a listening socket on the specified port; without a listening socket, the SYN gets an RST instead of a SYN-ACK. Check which process is listening with ss -tlnp | grep PORT.

When it breaks: If you forget to start the server before connecting → Connection refused immediately. If the port is used by another process → Address already in use. These two errors account for >50% of junior developers' debugging questions.

# Terminal 1 — start the TCP server
nc -l 9000

# Terminal 2 — connect a TCP client
nc 127.0.0.1 9000
# Type any text → it appears in Terminal 1
# Ctrl+C to close

Observe with:

ss -tlnp | grep 9000  # See which process is listening on port 9000
sudo tcpdump -i lo -n 'port 9000' -v  # Capture packets on loopback while connecting

Step 2 — Capture the 3-way handshake with tcpdump

TCP only transfers data after the 3-way handshake completes: the client sends SYN, the server answers with SYN-ACK, and the client confirms with ACK. Capturing packets on loopback with sudo tcpdump -i lo -n 'port 9000' -v shows exactly these three packets every time nc connects to the server. Reading the Flags column helps you tell a successful connection apart from one that got an RST or had its packets dropped.

RFC 9293 §3.1 defines the TCP control bits in the header: SYN (bit 1), ACK (bit 4), FIN (bit 0), RST (bit 2). tcpdump uses the notation: [S]=SYN, [S.]=SYN-ACK (SYN+ACK), [.]=ACK, [F.]=FIN-ACK, [R]=RST. The 3-way handshake you observe is [S] → [S.] → [.] — only after that does data transfer start.

When it breaks: If you only see SYN and no SYN-ACK → a firewall, or the server is not listening. If you see SYN + RST → the port is closed. If you see nothing → the packet is being dropped (firewall DROP). Telling these 3 patterns apart is a core network debugging skill.

# Terminal 1 — capture on loopback
sudo tcpdump -i lo -n 'port 9000' -v

# Terminal 2 — start the server
nc -l 9000

# Terminal 3 — connect to see the handshake
nc 127.0.0.1 9000
# tcpdump shows: SYN → SYN-ACK → ACK

Observe with:

sudo tcpdump -i lo -n 'port 9000' -v  # Flag: [S]=SYN, [S.]=SYN-ACK, [.]=ACK, [R]=RST
# Reading the output: client:port > server:port Flags [S], seq N

Step 3 — Try UDP — no handshake

UDP is a connectionless protocol: there is no handshake, and the very first datagram already carries data. With nc -u, text typed on the client appears on the server immediately, with no handshake first. Because there is no connection state, sending UDP to a port that is not open (for example 9001) does not report an error on the sending side either — completely unlike TCP, which is refused immediately.

When it breaks: Sending UDP when no server is listening → no error on the sending side (unlike TCP, which is refused immediately). The destination kernel sends ICMP Port Unreachable — but if a firewall blocks ICMP, the sender learns nothing. Debugging UDP failures is harder than TCP because there is no connection state.

# Terminal 1 — UDP server
nc -u -l 9000

# Terminal 2 — UDP client (no handshake)
nc -u 127.0.0.1 9000
# Type text → it appears in Terminal 1 immediately, no handshake needed first

# Compare: send UDP when there is no server
nc -u 127.0.0.1 9001  # port not open
echo 'hello' | nc -u 127.0.0.1 9001  # sends without reporting an error

Observe with:

sudo tcpdump -i lo -n 'port 9001' -v  # See UDP datagrams without handshake flags
ss -ulnp  # Check which UDP sockets are listening

Symptoms when it breaks:

How to fix:

  1. Use tcpdump to confirm whether the UDP packets are actually being sent

    sudo tcpdump -i lo -n 'udp port 9001' -c 5
    
  2. If you need a delivery guarantee with UDP, implement sequence numbers at the application layer

    # No OS command — this is logic you must implement in application code
    

Step 4 — Compare TCP vs UDP with Wireshark / tcpdump

Wireshark shows the RTTs exactly: with TCP, the first 3 packets are the handshake before any data. With UDP, data appears in the very first packet. This is direct evidence of the latency trade-off.

When it breaks: If you capture only one side and see no ACK → the network is asymmetric (packets in one direction are blocked). Common when debugging cloud VMs: inbound OK but outbound blocked by a security group → the SYN goes out but no SYN-ACK comes back.

# Capture TCP and UDP at the same time
sudo tcpdump -i lo -n 'port 9000 or port 9001'

# Open 2 server/client pairs (TCP port 9000, UDP port 9001)
# TCP: nc -l 9000  /  nc 127.0.0.1 9000
# UDP: nc -u -l 9001  /  nc -u 127.0.0.1 9001

# Observe: TCP starts with 3 lines SYN/SYN-ACK/ACK
# UDP starts directly with a data packet

Observe with:

sudo tcpdump -i lo -n 'port 9000 or port 9001'  # Compare side by side
# TCP: see [S] [S.] [.] before data | UDP: see the data packet first, immediately

Step 5 — Check listening ports — tell TCP from UDP

ss/netstat distinguish tcp from udp in their output. When debugging 'connection refused', the first step is to check which process is listening on which port, and with which protocol.

When it breaks: The service runs on UDP but the client connects over TCP → refused immediately. This happens with misconfiguration: a DNS server (UDP 53) tested with nc (TCP by default) → refused, yet DNS is still working. Check the right protocol before concluding the service is down.

# Show all listening ports (both TCP and UDP)
ss -tlunp

# TCP only
ss -tlnp | grep LISTEN

# UDP only
ss -ulnp

# Show which process binds a specific port
sudo ss -tlnp | grep ':80'

Observe with:

ss -tlunp  # t=TCP, u=UDP, l=listening, n=numeric, p=process
# The output clearly distinguishes 'tcp' vs 'udp' in the first column

Step 6 — DNS query over UDP — see why TCP is not needed

DNS is the most classic example of UDP: the query and response fit into 1 packet <512 bytes. Use dig with +tcp to compare latency — TCP clearly adds handshake overhead.

RFC 1035 §2.3.4 defines the 512-byte limit for DNS messages over UDP — the reason DNS is the most classic example of UDP: the query and response usually fit in 1 small datagram, so the overhead of the TCP 3-way handshake outweighs the benefit. DNS falls back to TCP when the response exceeds 512 bytes (or EDNS0 extends the limit to 4096 bytes per RFC 6891).

When it breaks: A firewall blocks outbound UDP 53 → every DNS query times out → every service that depends on domain resolution fails. Sign: ping by IP works but ping by hostname times out. Verify: if dig @8.8.8.8 google.com gets no answer → the firewall is blocking UDP 53.

# DNS queries use UDP by default
dig google.com

# Force DNS over TCP to compare
dig +tcp google.com

# Capture the DNS query (UDP port 53)
sudo tcpdump -i any -n 'port 53' &
dig google.com
sudo pkill tcpdump
# You see: 1 query packet + 1 response packet (UDP, no handshake)

Observe with:

sudo tcpdump -i any -n 'port 53'  # Capture DNS: see UDP vs TCP handshake
dig google.com  # Default UDP
dig +tcp google.com  # Force TCP — count the extra packets

Step 7 — TCP FIN handshake — closing a connection properly

Closing a TCP connection is its own exchange too: each direction sends a FIN and gets it ACKed — the connection is not simply cut off. The side that actively closes keeps the socket in the TIME_WAIT state for a while longer, so ss -tn still shows the entry even though the connection has ended. Understanding TIME_WAIT explains the 'Address already in use' error when you restart a service right away, and why you should reuse connections with keepalive/connection pools.

When it breaks: Restarting a service right after stopping it → 'Address already in use' because the port is still in TIME_WAIT. Fix: SO_REUSEADDR (most production servers already set it). If you see too many TIME_WAIT sockets → connections may not be reused (missing keepalive/connection pool).

# Show TCP states when a connection closes
ss -tn

# Show TIME_WAIT (appears right after a connection closes)
ss -tn | grep TIME-WAIT

# Fix 'Address already in use' during development: SO_REUSEADDR
# (nginx and node.js both set this flag by default)

Observe with:

ss -tn state time-wait  # Show connections in TIME_WAIT
watch -n1 'ss -tn | grep TIME-WAIT | wc -l'  # Count in real time while opening/closing connections

Symptoms when it breaks:

How to fix:

  1. Check the current number of TIME_WAIT sockets

    ss -tn state time-wait | wc -l
    
  2. Show the kernel's ephemeral port range

    cat /proc/sys/net/ipv4/ip_local_port_range
    
  3. Widen the ephemeral port range to get more ports (a temporary measure; tuning keepalive/pooling is the real solution)

    sudo sysctl -w net.ipv4.ip_local_port_range='1024 65535'
    
  4. Enable tcp_tw_reuse to reuse TIME_WAIT sockets for outbound connections (safe when timestamps are enabled)

    sudo sysctl -w net.ipv4.tcp_tw_reuse=1
    

Scripted: Run on a production server when you suspect TIME_WAIT exhaustion or a connection pool leak. Output: timestamp + count of each TCP state (ESTAB, TIME-WAIT, CLOSE-WAIT...). Default interval is 2s; pass an argument to change it: ./watch-tcp-states.sh 5

#!/bin/bash
# watch-tcp-states.sh — Monitor TCP state counts in real time
# Use when debugging TIME_WAIT exhaustion or tracking a connection leak
INTERVAL=${1:-2}
echo "Monitoring TCP states every ${INTERVAL}s (Ctrl+C to stop)"
echo "---"
while true; do
  echo "$(date '+%H:%M:%S')  $(ss -tn | awk 'NR>1{print $1}' | sort | uniq -c | sort -rn | tr '\n' '  ')"
  sleep "$INTERVAL"
done

Common misconceptions

Understanding the latency penalty of TCP retransmits correctly lets you pick the right protocol: video calls use UDP because losing 1 frame is better than waiting 1+ seconds for a retransmit that causes a freeze. QUIC solves this by isolating retransmits at the stream level.

Binary thinking of TCP=reliable/UDP=unreliable leads to misunderstanding the QUIC/WebRTC architecture. HTTP/3 uses UDP yet is more reliable than HTTP/2-over-TCP on lossy networks because it has no transport-level HOL blocking.

sysctl tcp_tw_recycle (removed from the Linux kernel in 4.12) caused real production bugs with NAT — connections from the same NAT gateway were dropped because of unsynchronised timestamps. Do not disable TIME_WAIT in production.

Configuring a container/systemd service to bind port 80/443 without running as root: use setcap cap_net_bind_service=+ep on the binary, or authbind. Understanding the real reason helps you configure the right capabilities instead of escalating privileges unnecessarily.

The mitigation strategy depends on identifying the root cause correctly: if you think it is RAM → adding RAM will not solve it; you must enable SYN cookies (net.ipv4.tcp_syncookies=1) and enlarge the backlog queue to absorb bursts.

Try at home

1. See the 3-way handshake — SYN/SYN-ACK/ACK — with your own eyes before any data flows

# Terminal 1: start TCP server
nc -l 9000

# Terminal 2: capture
sudo tcpdump -i lo -n 'port 9000' -v

# Terminal 3: connect
nc 127.0.0.1 9000

Observe: # In the tcpdump output, look at the flags:

2. See that UDP has no handshake — data goes straight out without any handshake

# Terminal 1: UDP server
nc -u -l 9001

# Terminal 2: capture
sudo tcpdump -i lo -n 'port 9001' -v

# Terminal 3: UDP client
nc -u 127.0.0.1 9001

Observe: # In tcpdump: the very first packet is DATA ss -ulnp | grep 9001 # Verify the UDP server is listening

3. See that DNS uses UDP (port 53) — query + response are just 2 packets, no handshake

sudo tcpdump -i any -n 'port 53' &
dig google.com
sudo pkill tcpdump
# Compare: dig +tcp google.com (force TCP, you see a SYN first)

Observe: # UDP DNS: only 2 lines in tcpdump (query + response) dig +stats google.com # Look at 'SERVER:' and 'Query time:' to compare latency

4. Check listening ports to tell TCP from UDP — a basic debugging skill

# Show all TCP ports in LISTEN
ss -tlnp

# Show all UDP sockets
ss -ulnp

# Show which process binds a specific port
sudo ss -tlnp | grep ':80'

Observe: # First column: 'tcp' or 'udp' — this is how you tell them apart

5. Reproduce 'connection refused' vs 'connection timeout' — the 2 most common errors

# Connection refused: no process listening on the port
nc -vz 127.0.0.1 65533

# Connection timeout: IP does not exist or firewall drops
nc -vz -w 3 203.0.113.254 80

# Observe the response time: refused immediately, timeout after 3s

Observe: # Refused: answers immediately in <10ms — the kernel sends an RST time nc -vz 127.0.0.1 65533 # Measure the refused time time nc -vz -w 2 203.0.113.254 80 # Measure the timeout time

6. Look at TCP states on the system — understand ESTABLISHED, TIME_WAIT, LISTEN

# Show all TCP connections with their state
ss -tn

# Filter by state
ss -tn state established
ss -tn state time-wait

# Watch in real time while opening/closing connections
watch -n1 'ss -tn | head -20'

Observe: # After closing the nc connection: watch TIME-WAIT appear

Review questions

Question 1. Why does DNS use UDP instead of TCP?

  1. UDP is more secure than TCP
  2. DNS queries are small and need to be fast — avoiding the 3-way handshake overhead
  3. TCP does not support port 53
  4. UDP guarantees delivery better than TCP

Answer: DNS queries are small and need to be fast — avoiding the 3-way handshake overhead. A DNS query is usually <512 bytes and needs an answer within a few ms. With TCP, 3 handshake packets would be spent before every query — nearly doubling latency. At billions of queries per second, saving the handshake = enormous savings.

Question 2. In what order does the TCP 3-way handshake happen?

  1. SYN-ACK → SYN → ACK
  2. ACK → SYN → SYN-ACK
  3. SYN → SYN-ACK → ACK
  4. SYN → ACK → DATA

Answer: SYN → SYN-ACK → ACK. The client sends SYN (requests a connection). The server replies with SYN-ACK (agrees + requests in the reverse direction). The client sends ACK (acknowledges). This order ensures both directions work before any data flows.

Question 3. A 'Connection refused' error appears when you curl a server. What is the most likely cause?

  1. A firewall is blocking packets
  2. DNS cannot resolve the hostname
  3. No process is listening on that port
  4. The network cable is cut

Answer: No process is listening on that port. 'Connection refused' = the TCP SYN reached the destination machine but the kernel sent an RST because no process is listening on that port. It means the machine is up and IP routing is fine, but the service is not running (or is running on the wrong port).

Question 4. HTTP/3 uses UDP instead of TCP — why not use TCP like HTTP/1 and HTTP/2?

  1. UDP is faster and HTTP/3 does not need reliability
  2. TCP has Head-of-Line blocking — losing 1 packet blocks the whole connection
  3. IANA recommends UDP for HTTPS
  4. TCP does not support port 443

Answer: TCP has Head-of-Line blocking — losing 1 packet blocks the whole connection. HTTP/2 multiplexes many streams over 1 TCP connection. When 1 TCP packet is lost, the whole connection must wait for the retransmit — even unrelated streams are blocked (Head-of-Line blocking). QUIC over UDP handles each stream independently.

Question 5. Well-known ports (0–1023) require root to bind — why?

  1. To improve network performance
  2. To protect against ordinary users impersonating system services (SSH, HTTP)
  3. Because low port numbers need dedicated kernel memory
  4. IANA mandates that only the kernel may use them

Answer: To protect against ordinary users impersonating system services (SSH, HTTP). If any user could bind :22, they could create a fake SSH server — and harvest credentials. Only a root process can be trusted to run the real SSH. That is why nginx in production runs as root and then drops privileges after binding :80/:443.

Question 6. You are debugging a multiplayer game with high lag. The developer says 'the server uses TCP'. What could the problem be?

  1. TCP does not support many concurrent connections
  2. TCP retransmits when packets are lost — this increases latency uncontrollably in a game
  3. Games cannot use TCP, only UDP
  4. The TCP header is too large and causes congestion

Answer: TCP retransmits when packets are lost — this increases latency uncontrollably in a game. In a game, every old position frame is worthless once a new frame arrives. TCP retransmitting an old packet delays every new packet after it (Head-of-Line blocking). Games should use UDP and handle loss themselves — skip old frames and care only about the latest one.

Question 7. What happens when you send a UDP packet to a port with no process listening?

  1. The packet is dropped silently, with no response at all
  2. The connection times out after 30 seconds
  3. An ICMP Port Unreachable is sent back
  4. The OS automatically redirects to another port

Answer: An ICMP Port Unreachable is sent back. When a UDP packet arrives at a port that is not listening, the kernel sends ICMP Type 3 Code 3 (Port Unreachable) back to the sender. This is why 'nc -u 127.0.0.1 [closed-port]' usually gets an ICMP error immediately — unlike a TCP RST.

Question 8. What is the sequence number in TCP used for?

  1. Identifying the connection (instead of the IP)
  2. Guaranteeing order and detecting packet loss for retransmission
  3. Encrypting data
  4. Counting bytes sent to compute bandwidth

Answer: Guaranteeing order and detecting packet loss for retransmission. The sequence number numbers every byte. The receiver knows which packets are missing (it ACKs the last contiguously received packet). When the network reorders packets, the receiver uses the seq number to put them back in the correct order. This is the core mechanism that makes TCP reliable.

Flashcards

  1. Server → Client: SYN-ACK (seq=Y, ack=X+1)
  2. Client → Server: ACK (ack=Y+1) Then data starts flowing. These 3 steps ensure both directions, client→server and server→client, are open before real data is sent. With only 1 step (SYN+DATA), the server might receive data while the client has no idea whether the server received it.