Skip to content

Lesson 6 of 18How software works

Networking You Will Actually Debug

IP addresses, ports, localhost vs 0.0.0.0, TCP vs UDP, and the curl, dig, nc and lsof commands that find out why something cannot connect.

15 min read0/5 questions

"It works on my machine, but not from the browser." "The app cannot reach the database." "The API times out, but only in staging." Network problems are some of the most common tickets you will pick up, and they feel mysterious until you see that each one fails at a specific layer: the name did not resolve, the port was closed, the connection was blocked, the certificate was wrong, or the server answered with an error. How the Web Works told the story of a page load from DNS to render. This lesson is the practical side: the addresses and ports involved, why localhost sometimes lies to you, and a handful of commands that tell you exactly which layer is broken.

IP addresses, private networks and NAT

You already know that an IP address identifies a machine on a network. Two details matter at work.

First, a large chunk of IPv4 space is reserved as private: these addresses are used inside homes, offices and cloud networks, and are never routed on the public internet. There are three ranges:

RangeCIDRTypical use
10.0.0.0 to 10.255.255.25510.0.0.0/8cloud networks (AWS VPCs), big offices
172.16.0.0 to 172.31.255.255172.16.0.0/12Docker's default networks
192.168.0.0 to 192.168.255.255192.168.0.0/16home routers

That notation is CIDR: an address, a slash, and how many leading bits are fixed. An IPv4 address is 32 bits, so /24 fixes the first 24 bits (the first three numbers) and leaves 8 bits, 256 addresses, for the machines on that network. /16 leaves 16 bits: 65,536 addresses. A smaller number after the slash means a bigger network. /32 is exactly one address, and 0.0.0.0/0 means "every address", which you will see in firewall rules (usually as something to be careful with).

Python
import ipaddress net = ipaddress.ip_network("192.168.1.0/24")print(net.netmask, net.num_addresses)print(ipaddress.ip_address("192.168.1.42") in net)print(ipaddress.ip_address("192.168.2.42") in net) PRIVATE = [ipaddress.ip_network(n) for n in ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]]for addr in ["10.0.3.7", "172.20.0.5", "172.32.0.5", "192.168.1.42", "8.8.8.8"]: ip = ipaddress.ip_address(addr) print(f"{addr:<14} private: {any(ip in n for n in PRIVATE)}")
Output
Press Run (⌘ Enter) to see what happens.

Notice 172.32.0.5 is not private: the /12 range stops at 172.31.255.255. People get that one wrong.

Second, your laptop's address is probably private, something like 192.168.1.42. Your home router has one public address from your internet provider, and it rewrites every outgoing packet so it looks like it came from that public address, then sends replies back to the right device. This is NAT (network address translation). It is why the IP your laptop reports is not the IP a website sees, and why a server running on your laptop is not reachable from the internet by default. Cloud servers in private subnets reach the internet through a NAT gateway for the same reason.

ipconfig getifaddr en0        # macOS: your laptop's address on Wi-Fiip addr                       # Linux: all interfaces and their addressescurl https://ifconfig.me      # your PUBLIC address, as a website sees it

IPv6 addresses are 128 bits, written in hex like 2606:4700:10::6814:179a (:: means "a run of zeros"). There are so many that NAT is not needed, and its loopback address is ::1. More and more networks are dual-stack, so tools often try IPv6 first, as you will see in the curl output below.

Predict the outputPython

What does this print?

import ipaddress
print(ipaddress.ip_network("10.0.0.0/16").num_addresses)
Need a nudge? Hints walk you through it.

Ports: many programs, one address

An IP address gets traffic to a machine. A port gets it to the right program on that machine. A port is just a number from 0 to 65535. A server listens on a port, and clients connect to address:port. Ports below 1024 are traditionally reserved for standard services and need admin rights to listen on.

Match the pairs0/6 matched

Match each port to what usually listens on it.

Choose an item, then its match on the other side.

Only one process can listen on a given address and port at a time. Start a second dev server on the same port and you get an error that every engineer knows:

python3 -m http.server 8000# OSError: [Errno 48] Address already in use      (errno 98 on Linux)node server.js# Error: listen EADDRINUSE: address already in use :::3000

Usually the culprit is an old copy of your own server still running in another terminal or in the background. Find it with lsof ("list open files"; on Unix, network connections count as files):

lsof -i :8000# COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME# Python  45772 sam     3u  IPv4  0x...       0t0  TCP localhost:irdmi (LISTEN)lsof -nP -iTCP:8000 -sTCP:LISTEN    # -n -P: show numbers, not names# Python  45772 sam     3u  IPv4  0x...       0t0  TCP 127.0.0.1:8000 (LISTEN)kill 45772                          # SIGTERM, from the previous lesson

lsof is built into macOS and available on most Linux machines (ss -ltnp is the modern Linux alternative). Without -P, lsof swaps port numbers for service names from a lookup table, which is why you sometimes see a strange name instead of 8000.

localhost vs 0.0.0.0

Every machine has a loopback network interface that only talks to itself. Its address is 127.0.0.1 (and ::1 in IPv6), and localhost is the name for it. Traffic to it never leaves the machine.

When a server starts, it chooses which address to listen on, called its bind address:

  • Bind to 127.0.0.1: only programs on this same machine can connect. Safe, and the default for many dev servers.
  • Bind to 0.0.0.0: listen on all interfaces, so other machines (and other containers) can connect too.

0.0.0.0 is a bind address, not a place to visit. You bind a server to 0.0.0.0, then browse to localhost or the machine's real IP. (Typing 0.0.0.0 in a browser happens to work on some systems, but do not rely on it.)

This explains the most common Docker networking bug:

Works inside the container, not from your browser
Browser: localhost:8000Browserlocalhost:8000Your laptop: port 8000 publishedYour laptopport 8000 publishedContainer network: 172.17.0.2Container network172.17.0.2App in container: bound to 127.0.0.1App in containerbound to 127.0.0.1connect-p 8000:8000blocked

Inside the container, the app listens on 127.0.0.1:8000. curl localhost:8000 inside the container works, so it looks fine.

1/5
Quick check
A teammate on the same office Wi-Fi cannot open your dev server at http://192.168.1.42:3000, but it works for you at localhost:3000. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

TCP, UDP, and what "refused" and "timeout" mean

Most traffic you deal with uses one of two transport protocols:

  • TCP gives you a reliable, ordered stream of bytes. It retransmits lost packets and puts them back in order. HTTP/1.1, HTTP/2, SSH and database connections use it.
  • UDP just sends individual packets (datagrams) with no guarantees: they may be lost, duplicated or reordered. In exchange there is no setup and no waiting for lost packets. DNS lookups, video calls, online games and HTTP/3 use it.

A TCP connection starts with a three-step handshake, and the way it fails tells you a lot:

The TCP handshake, and two ways it fails
ClientServerSYNSYN-ACKACKSYN to port 5433RSTSYN, no reply

Asking to connect to port 5432.

1/6

This distinction is one of the most useful things in this lesson. Refused is fast and means "you reached the machine, wrong port or service down". Timeout is slow and means "your packets are going nowhere": look at firewalls, cloud security groups (AWS's per-server firewall rules), network routes, or whether you are using a private IP from outside its network.

Quick check
Your app in AWS connects to a new database and hangs for 30 seconds before failing with a timeout. The database is definitely running. What do you check first?
Need a nudge? A hint rules out a wrong answer.

HTTP/1.1, HTTP/2 and HTTP/3

You only need to recognise these:

VersionRuns overKey idea
HTTP/1.1TCPOne request at a time per connection; browsers open several connections.
HTTP/2TCPMany requests share one connection at once (multiplexing), headers compressed.
HTTP/3QUIC over UDPLike HTTP/2, but a lost packet no longer stalls every stream; faster connection setup.

Your code rarely changes between them, since the methods, headers and status codes are the same. They show up in the curl -v output and in the browser's Network tab, and HTTP/3 explains why a firewall that blocks UDP can make some sites fall back to HTTP/2.

The toolkit

Here are the commands, roughly in the order you reach for them. They all ship with macOS. On Linux, dig comes in the dnsutils or bind-utils package and nc in netcat-openbsd. On Windows, curl and nslookup are built in, and tracert replaces traceroute.

dig +short example.com          # DNS: what IP does this name resolve to?# 104.20.23.154# 172.66.147.243nslookup example.com            # the same question, available everywhereping -c 3 example.com           # is the host reachable at all? (Ctrl+C to stop without -c)# 64 bytes from 104.20.23.154: icmp_seq=0 ttl=52 time=23.4 msnc -zv localhost 5432           # is anything listening on this port?# Connection to localhost port 5432 [tcp/postgresql] succeeded!nc -zv localhost 5433# nc: connectx to localhost port 5433 (tcp) failed: Connection refusedcurl -I https://example.com     # just the response status and headerstraceroute example.com          # every router hop on the way there

Two cautions. Many servers block ping (it uses a protocol called ICMP), so no reply does not prove a host is down. And your addresses will differ from these: big sites have many IPs that change.

Reading curl -v

curl -v ("verbose") shows every stage of a request. Lines starting with * are curl telling you what it is doing, > is what you sent, and < is what came back. Here is real output, trimmed:

curl -v -o /dev/null https://example.com# * Host example.com:443 was resolved.               <- 1. DNS worked# * IPv6: 2606:4700:10::ac42:93f3, 2606:4700:10::6814:179a# * IPv4: 104.20.23.154, 172.66.147.243# *   Trying [2606:4700:10::ac42:93f3]:443...# * Connected to example.com (2606:4700:10::ac42:93f3) port 443   <- 2. TCP connected# * ALPN: curl offers h2,http/1.1# * SSL connection using TLSv1.3 / ...               <- 3. TLS handshake done# * Server certificate:# *  subject: CN=example.com# *  SSL certificate verify ok.                      <- 4. certificate is valid# * using HTTP/2# > GET / HTTP/2                                     <- 5. your request# > Host: example.com# > User-Agent: curl/8.7.1# ># < HTTP/2 200                                       <- 6. the response status# < content-type: text/html; charset=utf-8# < alt-svc: h3=":443"; ma=86400                     <- "I also speak HTTP/3"

When something breaks, the output simply stops at the broken stage, and curl's exit code names it:

curl https://no-such-host.example/# curl: (6) Could not resolve host: no-such-host.examplecurl http://localhost:9/# curl: (7) Failed to connect to localhost port 9 after 0 ms: Couldn't connect to servercurl --connect-timeout 3 http://10.255.255.1/# curl: (28) Failed to connect to 10.255.255.1 port 80 after 3006 ms: Timeout was reachedcurl https://expired.badssl.com/# curl: (60) SSL certificate problem: certificate has expired

Error 6 is DNS, 7 is refused, 28 is a timeout, and 60 is a certificate problem. You can also time each stage, which is the first thing to do when someone says "the API is slow":

curl -s -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} total=%{time_total}\n' https://example.com# dns=0.001851 connect=0.021146 tls=0.046733 total=0.073546

Each number is the time in seconds from the start until that stage finished. If most of the total comes after tls, the server itself is slow, not the network.

A debugging ladder

When something "cannot connect", climb the layers from the bottom and stop at the first one that fails. Each rung has a command that answers it in seconds:

RungQuestionCheck withFailure looks like
1Does the name resolve, to the IP you expect?dig +short hostcurl error 6
2Is the port open and reachable?nc -zv host portrefused (7) or timeout (28)
3Is TLS happy?curl -vcurl error 60, hostname mismatch
4What status came back?curl -I or curl -v401, 403, 404, 500, 502
5Is the body what you expected?curl and read itwrong JSON, an HTML error page

The point of the ladder is to stop guessing. "Is it the code?" is rung 5. If rung 2 fails, no code change will help, and you have saved an afternoon.

Put it in order5 steps

A request to an internal API fails. Put the checks in the order you should run them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
private IP range
Addresses reserved for internal networks: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Not routed on the internet.
CIDR
Notation like 10.0.0.0/16: the number after the slash is how many leading bits are fixed. Smaller number, bigger network.
NAT
A router rewriting private addresses to one public address, so many devices share it.
port
A number from 0 to 65535 that picks which program on a machine receives the traffic.
bind address
The address a server listens on. 127.0.0.1 means this machine only; 0.0.0.0 means every interface.
TCP vs UDP
TCP is a reliable ordered stream with a handshake. UDP sends independent packets with no guarantees.
refused vs timeout
Refused: the host answered but nothing listens on the port. Timeout: no answer at all, often a firewall.