Sub topic 4
Reaching the server: IP and TCP connections
This chapter assumes you can read a URL and know that DNS turns a hostname into an IP address. It also assumes you can run commands in a terminal. It covers what happens next: how the browser gets bytes to that address and keeps them in order, so HTTP messages can travel.
Where this fits
DNS gave the browser an address such as 93.184.216.34. The browser still has no way to send an HTTP request. Two layers sit between the address and HTTP.
- IP (Internet Protocol) moves packets from one address to another.
- TCP (Transmission Control Protocol) builds a reliable, ordered byte stream on top of IP.
HTTP/1.1 and HTTP/2 assume that stream. HTTP/3 replaces TCP with QUIC, which is covered in a later chapter.
IP addressing
An IP address identifies a network interface. A packet is a small chunk of data with a header that holds the source and destination addresses. Routers read the destination and forward the packet one hop at a time. No router knows the whole path.
| Version | Example | Size | Notes |
|---|---|---|---|
| IPv4 | `93.184.216.34` | 32 bits | Addresses are scarce, so NAT is common |
| IPv6 | `2606:2800:220:1:248:1893:25c8:1946` | 128 bits | Written in hexadecimal groups, with `::` shortening zero runs |
Some address ranges are private and do not route on the public internet. Examples are 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. Your laptop probably has an address like 192.168.1.20. Your router uses NAT (Network Address Translation) to share one public address among many devices.
IP alone gives no guarantees. Packets can be lost, duplicated, delayed, or arrive out of order. IP also has no concept of which program should receive a packet.
Ports
A port is a 16-bit number (0 to 65535) that identifies a program on a host. An IP address picks the machine. The port picks the program.
A connection is identified by four values: client IP, client port, server IP, server port. The server port is usually well known. The client port is chosen by the operating system from a high range, and is called an ephemeral port.
| Port | Default for |
|---|---|
| 80 | HTTP |
| 443 | HTTPS |
| 22 | SSH |
| 53 | DNS |
When a URL has no port, the browser uses the scheme's default. https://example.com/ means port 443.
What TCP adds
TCP gives each side a byte stream with these properties:
- Reliable. Lost data is detected and sent again.
- Ordered. The receiver sees bytes in the order they were sent.
- Flow controlled. A sender cannot overwhelm a slow receiver.
- Congestion controlled. A sender slows down when the network is crowded.
TCP does not preserve message boundaries. If you send two HTTP requests, the receiver may read them as one chunk or as five. This is why HTTP needs its own rules, such as Content-Length, to say where a message ends.
The three-way handshake
Before data flows, the two sides agree on starting sequence numbers. This takes three packets.
- SYN. The client proposes a starting sequence number.
- SYN-ACK. The server acknowledges it and proposes its own.
- ACK. The client acknowledges the server's number.
The client can send data right after its ACK. The handshake costs one round trip before the first request. On a link with 80 ms round-trip time, that is 80 ms spent before any HTTP bytes move. With HTTPS, TLS adds more round trips on top, which the HTTPS chapter covers.
Connection states
A TCP connection moves through states. You will see their names in tools like ss and netstat.
Closing uses FIN packets, one in each direction. The side that closes first ends in TIME_WAIT, which holds the connection's four-value identity for a while (often 60 seconds on Linux) so stray late packets are not mistaken for a new connection. Many TIME_WAIT entries on a busy server are normal, but they show why reusing connections is cheaper than opening new ones.
Seeing a connection yourself
You can open a TCP connection and speak HTTP by hand. This Python script does exactly what a browser does at a low level.
import socket
host = "example.com"
with socket.create_connection((host, 80), timeout=5) as sock:
print("local:", sock.getsockname())
print("remote:", sock.getpeername())
request = (
"GET / HTTP/1.1\r\n"
f"Host: {host}\r\n"
"Connection: close\r\n"
"\r\n"
)
sock.sendall(request.encode("ascii"))
chunks = []
while True:
data = sock.recv(4096)
if not data:
break
chunks.append(data)
response = b"".join(chunks)
print(response.split(b"\r\n", 1)[0].decode())create_connection resolves the name with DNS, then performs the handshake. The local line shows your ephemeral port. The loop calls recv until it returns empty bytes, which means the server closed its side. Because Connection: close was sent, the server closes after the response. The last line prints the status line, for example HTTP/1.1 200 OK.
A callout on the stream behavior:
Observing the handshake with curl
curl -v shows the connection steps before the HTTP exchange.
curl -v http://example.com/ -o /dev/nullLook for lines like these:
Trying 93.184.216.34:80...is the address chosen from DNS.Connected to example.com (93.184.216.34) port 80means the handshake finished.- Lines starting
>are the request. Lines starting<are the response.
To see only timing, use the write-out option.
curl -s -o /dev/null -w "dns=%{time_namelookup} connect=%{time_connect} total=%{time_total}\n" http://example.com/time_connect includes DNS time. The difference between time_connect and time_namelookup is roughly one round trip, the handshake.
Persistent connections
Opening a connection per request wastes round trips. HTTP/1.0 did that by default. HTTP/1.1 keeps the connection open by default, so later requests skip the handshake. This is a persistent connection, or keep-alive.
Browsers also open several connections to one host in parallel, commonly up to six for HTTP/1.1. This works around the fact that HTTP/1.1 handles one request at a time per connection.
A new connection also starts slowly. TCP's congestion control begins with a small sending window and grows it as acknowledgments return. This is slow start. A reused connection that has already grown its window is faster than a fresh one, even when the handshake cost is ignored.
Common errors
Connection problems appear before any HTTP exists, so there is no status code. You see the failure in the tool instead.
| Symptom | Likely cause |
|---|---|
| `Connection refused` | The host is reachable, but nothing listens on that port, so the OS replied with a reset |
| `Connection timed out` | Packets get no reply, often a firewall dropping them or a host that is down |
| `Could not resolve host` | The failure happened earlier, in DNS |
| `Connection reset by peer` | The other side closed abruptly, for example a crashed process or a proxy limit |
| `Address already in use` | A server tried to listen on a port another process holds |
The difference between refused and timed out is useful. Refused is fast and means the machine answered. Timed out is slow and means silence.
Checking a port
You can test reachability and see who listens locally.
nc -vz example.com 443
ss -ltnThe first command attempts a handshake with port 443 and reports success or failure. The second lists listening TCP sockets on Linux. On macOS, use lsof -iTCP -sTCP:LISTEN -n -P.
Exercise
A request to a server fails instantly with "Connection refused", while another request to a different host hangs for 30 seconds and then reports "Connection timed out". What does each result suggest?
Show answer
"Connection refused" means a packet reached the machine and its operating system answered with a reset, so the host is up but no program listens on that port. "Connection timed out" means no reply arrived, which points to a down host, a wrong address, or a firewall silently dropping packets.
Exercise
Your network round-trip time is 100 ms. A page needs one new HTTP connection over plain HTTP, and the server responds immediately. About how long passes before the browser receives the first byte of the response, ignoring DNS and transmission time?
Show answer
About 200 ms. The handshake takes one round trip (100 ms) before the request can be sent. The request and response then take another round trip (100 ms).
Exercise
Why can a single recv call on a TCP socket return only half of an HTTP response?
Show answer
TCP is a byte stream without message boundaries. Data arrives in segments of whatever size the network delivered, so one read may return any portion of it. The program must keep reading until Content-Length bytes arrive, the message framing says it is complete, or the connection closes.