DevPath
Tracks

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.

ApplicationHTTP, DNS, TLS: what you write
TransportTCP or UDP, ports
InternetIP: addresses and routing
LinkEthernet, Wi-Fi: one hop
Each layer wraps the one above in its own header on the way down and unwraps it on the way up, and treats the payload as opaque bytes.

What happens when you open https://example.com/search?q=cache

  1. DNS: the resolver turns example.com into an IP address, checking caches first (browser, OS, your ISP), then asking authoritative servers. Answers carry a TTL.
  2. TCP handshake: SYN, SYN-ACK, ACK. One round trip, and both sides agree on starting sequence numbers.
  3. 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.
  4. HTTP request and response travel over that secure stream.
  5. 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.

Browser and OS cachehit ends here
ResolverISP or public DNS
Root serverpoints to .com
TLD serverpoints to example.com
Authoritative serverknows the IP
IP addresscached for its TTL
DNS resolution on a cache miss. Each server only knows where to look next, until the authoritative server answers. The answer is cached along the way until its TTL expires.

Step 2, the TCP handshake, is three messages.

ClientServerSYN (my starting sequence number is x)SYN-ACK (mine is y, I expect x+1)ACK (I expect y+1)
After one round trip both sides have agreed on starting sequence numbers, and the client can already send data with its ACK or right after it.

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.

ClientServerGET /search?q=cache HTTP/1.1, Host: example.comHTTP/1.1 200 OK, Content-Length: 5, body: hello
HTTP is request then response, one round trip. The server does its work in between, and the status line tells the client how it went.

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.
OperationTimeNotes
DNS lookup (uncached)~tens of msZero when cached locally
TCP handshake1 round tripPlus TLS: 1 more with TLS 1.3
Request/response on warm connection1 round tripKeep-alive saves the setup cost
Parsing a messageO(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))

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 /charge can 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

  1. 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.
  2. TCP versus UDP? TCP is connection-oriented, reliable, ordered, with congestion control. UDP is connectionless and unordered but has lower latency and overhead.
  3. What does idempotent mean, and which methods are? Repeating a request has the same effect as one. GET, PUT, DELETE are; POST generally is not.
  4. 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.
  5. 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

Related lessons