Networking Basics: TCP/IP, DNS, HTTP, TLS
How a request travels from a URL to a server: layers, DNS, TCP, TLS, and the exact anatomy of HTTP messages and status codes, with a hand-built parser.
beginner45 min#networking#tcp#dns#http#tls#status-codes
Prerequisites: How Computers Run Programs
Why it matters
Nearly every program you write talks to another machine: an API, a database, a payment provider. When something is slow or fails, the question "where in the chain did it break?" has an answer only if you know the chain. Interviewers also love "what happens when you type a URL and press Enter", because it tests breadth in one story.
Intuition
Sending a letter involves layers. You write the message (content), put it in an envelope with an address (routing), and a postal service moves it hop by hop. Networks work the same way, and each layer only cares about its own job and treats the layer above as an opaque payload.
DNS is the phone book: you know the name example.com, the network needs a number. TCP is a phone call with confirmation: it makes sure every word arrives, in order. TLS is a sealed envelope: even if someone intercepts it, they cannot read or alter it. HTTP is the conversation you have once the line is open: a request, then a response.
How it works
Layers (the TCP/IP model)
Application HTTP, DNS, TLS-protected traffic what you write
Transport TCP (reliable), UDP (fast, no promise) ports
Internet IP addresses, routing
Link Ethernet, Wi-Fi one hop
IP delivers packets to a machine on a best-effort basis; they may be lost, duplicated, or reordered. TCP builds a reliable ordered byte stream on top using sequence numbers, acknowledgements, and retransmission. UDP skips that, which suits video calls and DNS lookups where late data is useless. A port picks the program on the machine, such as 80 for HTTP and 443 for HTTPS.
What happens when you open https://example.com/search?q=cache
- DNS: the resolver turns
example.cominto an IP address, checking caches first (browser, OS, your ISP), then asking authoritative servers. Answers carry a TTL. - TCP handshake: SYN, SYN-ACK, ACK. One round trip, and both sides agree on starting sequence numbers.
- TLS handshake: the client checks the server's certificate against trusted authorities, and both sides derive shared session keys. After that, everything is encrypted and tamper-evident. The key idea: public-key cryptography proves identity and bootstraps a fast symmetric key.
- HTTP request and response travel over that secure stream.
- The connection is often kept alive for the next request.
Step 1 in more detail: if no cache has the answer, the resolver walks down the DNS hierarchy.
Step 2, the TCP handshake, is three messages.
Anatomy of an HTTP message
GET /search?q=cache HTTP/1.1 start line: method, target, version
Host: example.com headers: Name: value, one per line
Accept: text/html
blank line ends the headers
(body, optional)
HTTP/1.1 200 OK status line: version, code, reason
Content-Type: text/plain
Content-Length: 5
blank line
hello body: exactly 5 bytes
Over an open connection, one request and response look like this.
Lines end with CRLF (carriage return plus line feed). Content-Length tells the receiver where the body stops. Methods carry meaning: GET reads and must not change anything, POST creates or triggers actions, PUT replaces, DELETE removes. GET, PUT, and DELETE should be idempotent, meaning repeating them has the same effect as doing it once.
Status codes by class
- 2xx success: 200 OK, 201 Created, 204 No Content.
- 3xx redirect: 301 Moved Permanently, 304 Not Modified (cache is still valid).
- 4xx client error: 400 Bad Request, 401 Unauthorized (not authenticated), 403 Forbidden (authenticated but not allowed), 404 Not Found, 429 Too Many Requests.
- 5xx server error: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout.
| Operation | Time | Notes |
|---|---|---|
| DNS lookup (uncached) | ~tens of ms | Zero when cached locally |
| TCP handshake | 1 round trip | Plus TLS: 1 more with TLS 1.3 |
| Request/response on warm connection | 1 round trip | Keep-alive saves the setup cost |
| Parsing a message | O(n) | Linear in header and body size |
Code: build and parse HTTP by hand
HTTP/1.1 is plain text, so you can write a request and parse a response with string operations. No sockets are needed, which keeps the demo deterministic.
CRLF = "\r\n"
def build_request(method, target, host, headers=None, body=""):
lines = [f"{method} {target} HTTP/1.1", f"Host: {host}"]
for name, value in (headers or {}).items():
lines.append(f"{name}: {value}")
if body:
lines.append(f"Content-Length: {len(body.encode())}")
return CRLF.join(lines) + CRLF + CRLF + body
def parse_response(raw):
head, _, body = raw.partition(CRLF + CRLF)
start, *header_lines = head.split(CRLF)
version, code, reason = start.split(" ", 2)
headers = {}
for line in header_lines:
name, _, value = line.partition(":")
headers[name.strip().lower()] = value.strip() # names are case-insensitive
length = int(headers.get("content-length", len(body)))
return int(code), reason, headers, body[:length]
def status_class(code):
return {2: "success", 3: "redirect", 4: "client error", 5: "server error"}.get(code // 100, "other")
req = build_request("GET", "/search?q=cache", "example.com", {"Accept": "text/html"})
print(req.replace(CRLF, "|"))
raw = "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nno such page, extra bytes"
code, reason, headers, body = parse_response(raw)
print(code, reason, headers["content-type"], repr(body), status_class(code))const CRLF = "\r\n";
function buildRequest(method, target, host, headers = {}, body = "") {
const lines = [`${method} ${target} HTTP/1.1`, `Host: ${host}`];
for (const [name, value] of Object.entries(headers)) lines.push(`${name}: ${value}`);
if (body) lines.push(`Content-Length: ${Buffer.byteLength(body)}`);
return lines.join(CRLF) + CRLF + CRLF + body;
}
function parseResponse(raw) {
const split = raw.indexOf(CRLF + CRLF);
const head = raw.slice(0, split);
const body = raw.slice(split + 4);
const [start, ...headerLines] = head.split(CRLF);
const [, code, ...reasonParts] = start.split(" ");
const headers = {};
for (const line of headerLines) {
const i = line.indexOf(":");
headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim(); // names are case-insensitive
}
const length = Number(headers["content-length"] ?? body.length);
return [Number(code), reasonParts.join(" "), headers, body.slice(0, length)];
}
function statusClass(code) {
const classes = { 2: "success", 3: "redirect", 4: "client error", 5: "server error" };
return classes[Math.floor(code / 100)] ?? "other";
}
const req = buildRequest("GET", "/search?q=cache", "example.com", { Accept: "text/html" });
console.log(req.replaceAll(CRLF, "|"));
const raw = "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nno such page, extra bytes";
const [code, reason, headers, body] = parseResponse(raw);
console.log(code, reason, headers["content-type"], `'${body}'`, statusClass(code));Both versions print two lines. The first is the request with CRLF shown as pipes: GET /search?q=cache HTTP/1.1|Host: example.com|Accept: text/html||. The second is 404 Not Found text/plain 'no such page' client error. The parser used Content-Length to ignore the trailing extra bytes, exactly how real clients find the end of a body.
Common pitfalls
- Confusing 401 and 403: 401 means "I do not know who you are", 403 means "I know, and you may not".
- Using GET for actions: crawlers, prefetchers, and caches assume GET is safe. A GET that deletes data will eventually be triggered by one of them.
- Ignoring timeouts: a call without a timeout can hang forever. Set connect and read timeouts, and retry only idempotent requests.
- Retrying non-idempotent calls blindly: retrying a
POST /chargecan bill twice. Use an idempotency key. - Assuming DNS changes are instant: cached answers live until their TTL expires.
- Trusting HTTP without TLS: anyone on the path can read or modify plain HTTP.
Practice
Classify the code easy
Hint
Look at the first digit.
Show solution
Which class is 429? 4xx, a client error: the client sent too many requests. 503 is 5xx: the server is overloaded or down for maintenance. A client should retry 503 and 429 later, ideally honoring a Retry-After header, but should not retry 400 unchanged.
Parse a query string medium
Hint
Split on the ampersand, then on the first equals sign, then decode percent escapes.
Show solution
Take the target /search?q=hello%20world&page=2. Split at ?, split the query on &, split each pair at the first =, and percent-decode (urllib.parse.unquote in Python, decodeURIComponent in JavaScript). Result: q = "hello world", page = "2". Handle missing = and repeated keys.
Chunked bodies medium
Hint
Each chunk starts with its size in hexadecimal.
Show solution
When the length is not known up front, the server sends Transfer-Encoding: chunked: a hex size line, CRLF, that many bytes, CRLF, repeated, ending with a chunk of size 0. To parse, read the size line, convert from base 16, read that many bytes, skip the CRLF, and stop at 0.
Why does the first request feel slow? hard
Hint
Count the round trips before the first byte of the response.
Show solution
A cold HTTPS request pays for DNS (possibly several lookups), a TCP handshake (1 round trip), a TLS 1.3 handshake (1 round trip), and then the request itself (1 round trip). With 50 ms of latency that is roughly 150 ms or more before data arrives. Keep-alive, connection pooling, DNS caching, and a CDN closer to the user each remove some of those trips.
Interview questions
- What happens when you type a URL and press Enter? DNS resolves the name, TCP connects, TLS secures it, the browser sends an HTTP request, the server responds, the browser renders and fetches further resources.
- TCP versus UDP? TCP is connection-oriented, reliable, ordered, with congestion control. UDP is connectionless and unordered but has lower latency and overhead.
- What does idempotent mean, and which methods are? Repeating a request has the same effect as one.
GET,PUT,DELETEare;POSTgenerally is not. - How does HTTPS protect you? TLS authenticates the server via certificates, encrypts the traffic, and detects tampering. It does not hide the destination host from the network.
- What does 502 versus 504 mean? Both come from a gateway or proxy. 502 means it got an invalid response from upstream; 504 means upstream did not answer in time.
Interviewers look for: a coherent end-to-end story, correct use of status codes, and awareness that failures are normal on networks (timeouts, retries, idempotency).
Quick check
A user is logged in but requests an admin page they have no rights to. Which status code fits best?
Finished this lesson?
Further resources
- MDN: An overview of HTTP (docs)
- MDN: HTTP response status codes (docs)
- RFC 9110: HTTP Semantics (docs)
- Internet protocol suite (Wikipedia) (article)