Cheat sheet · Computer Networking for Developers: IP, TCP, DNS, HTTP and TLS

Networking for Developers cheat sheet

How a request travels from fetch() to res.end(): layers, IP, TCP, DNS, HTTP, TLS, proxies, live connections, and the tools to debug each step. Debug one layer at a time, from the bottom up.

Read the full series →

blogs · jp-blogs.vercel.app/cheatsheets/series/networking

Layers and encapsulationLesson 0 →

LayerDoesAddress
2 Link (Ethernet)Frames on one local networkMAC: next stop
3 Internet (IP)Packets between any two machinesIP: final stop
4 Transport (TCP, UDP)Right program, TCP adds orderPort
7 ApplicationHTTP, DNS, TLSName, URL
  • Each layer wraps the one above. A bare SYN is 74 bytes: 14 Ethernet, 20 IP, 40 TCP.
  • A connection is named by 4 values: source IP and port, destination IP and port.
  • TTL drops by 1 per router; at 0 the packet dies (traceroute uses this). MTU is usually 1500; 'small works, big hangs' means MTU.
  • A request costs DNS, TCP, TLS, then HTTP. Round trips beat bandwidth.

IPv4, CIDR and subnetsLesson 1 →

PrefixAddressesUsable
/816,777,21616,777,214
/1665,53665,534
/24256254
/266462
/3042
/321One host
  • Block size = 256 minus the mask in the cut octet. A /26 gives blocks at 0, 64, 128, 192.
  • Private: 10/8, 172.16/12 (only 172.16 to 172.31), 192.168/16. 100.64/10 is CGNAT, 127/8 loopback.
  • Blocks nest or are fully apart. Overlapping VPCs cannot be peered, so plan CIDR first.
  • Python is_private is not a safe SSRF check: use an allow list and check the resolved address.

Routing, NAT and IPv6Lesson 1 →

  • Routing picks the longest prefix match. 0.0.0.0/0 is the default route, used when nothing else matches.
  • Routers know only the next hop. Same subnet: ARP finds the MAC. Otherwise send to the gateway.
  • NAT rewrites source IP and port and keeps a table. It blocks inbound, breaks peer-to-peer, and times out idle flows. Docker MASQUERADE is NAT.
  • IPv6 is 128 bits, normal subnets are /64, no NAT needed. Handle both in code and storage.
ip route get ADDR
The route that really wins
ip -br addr
Addresses on this machine
traceroute -n HOST
Where the path ends

Watch out: Behind a proxy the logs show the proxy's IP. Read X-Forwarded-For only from your own proxies, counting from the right.

TCP and UDPLesson 2 →

  • Handshake: SYN, SYN-ACK, ACK, one round trip. Reuse connections (keep-alive, pools).
  • Every byte is numbered. Lost data is resent on a timer that doubles (0.2, 0.4, 0.8 s).
  • TCP is a byte stream: three sends can arrive as one recv. Frame messages yourself (length prefix).
  • Flow control = receiver's window (zero window: sender stops). Congestion control = sender's window, a sawtooth; full queues cause bufferbloat.
State / errorMeaning
RefusedRST at once: nothing listens (exit 7)
Timed outSilence: firewall drops the SYN (exit 28)
TIME_WAITNormal on the side that closed first, 60 s
CLOSE_WAITPeer closed, your code did not: a bug

Watch out: Always set connect, read and total timeouts: OS defaults take minutes (tcp_retries2 15 is about 15 min). UDP has no resend, order or error; 41 of 100 datagrams vanished silently.

DNSLesson 3 →

  • Resolver walks root, TLD, authoritative, then caches. A referral has no aa flag; the final answer does.
  • Every record has a TTL; nothing is pushed. Lower the TTL before a move, then wait it out.
  • Negative answers are cached too (SOA's last number). Create a record before anything queries it.
  • UDP 53, then TCP when the answer is truncated (tc). Firewalls must allow both.
AnswerMeaning
NXDOMAINName does not exist
NOERROR, empty (NODATA)Name exists, not for this type
SERVFAILResolver got no good answer from the authority
CNAME at apexNot allowed: SOA and NS sit there; use ALIAS
dig NAME +short
Quick answer
dig @NS NAME +norec
Ask one server, bypass caches
getent hosts NAME
What your program sees (/etc/hosts first)

HTTP/1.1, HTTP/2 and HTTP/3Lesson 4 →

VersionKey idea
1.1Text over TCP; one answer at a time; browsers open about 6 connections
2Binary frames, streams, HPACK on one connection; TCP still blocks all
3 (QUIC)UDP, per-stream order, TLS 1.3 built in, connection migration
  • 12 requests of 300 ms: 3.6 s on one HTTP/1.1 connection, 0.32 s on HTTP/2. HPACK cut headers from 548 to 42 bytes.
  • HTTP/2 is chosen by ALPN in the TLS handshake. HTTP/3 is learned from Alt-Svc. Keep HTTP/2 working; UDP can be blocked.
  • HTTP/2 headers are lowercase, :authority replaces Host, no Connection header.
  • 0-RTT can be replayed: allow it only for safe GETs.

Watch out: Random ECONNRESET on idle keep-alive: the server closed first. Keep the client idle timeout shorter than the server and load balancer (Node default 5 s). Retry idempotent calls once.

TLS and certificatesLesson 5 →

  • TLS gives confidentiality, integrity and authentication. TLS 1.3 costs one round trip after TCP and gives forward secrecy.
  • Client checks: chain to a trusted root, dates, name in SAN, key usage. The server must send the intermediate.
  • SNI (host name) is plain text; TLS 1.3 encrypts the certificate. HTTPS still shows the IP and host.
  • Let's Encrypt: HTTP-01 needs port 80, no wildcard. DNS-01 uses a TXT at _acme-challenge, allows wildcards. Certs are 90 days or less: automate and alert 14 days ahead.
ErrorUsual cause
UNABLE_TO_VERIFY_LEAF_SIGNATUREMissing intermediate (works in browsers only)
CERT_HAS_EXPIREDExpired, or wrong client clock
ERR_TLS_CERT_ALTNAME_INVALIDHost name not in SAN
DEPTH_ZERO_SELF_SIGNED_CERTSelf-signed or private CA

Watch out: Never use -k, rejectUnauthorized: false or NODE_TLS_REJECT_UNAUTHORIZED=0: they accept imposters. Trust the right CA. HSTS locks users out if the cert breaks, so start with a short max-age.

Proxies, load balancers, CDNLesson 6 →

ItemL4L7
SeesIP and portHTTP: path, headers
DoesCopies bytes, fastRoutes, retries, caches, adds XFF
  • Forward proxy serves clients (HTTPS via CONNECT). Reverse proxy serves servers.
  • Algorithms: round robin, weighted, least connections, hash. ip_hash is poor behind NAT. Prefer stateless over sticky sessions.
  • Health checks: passive (learn from failures) or active (probes). Keep /health shallow.
  • Retries can repeat payments: use idempotency keys. CDN: Cache-Control, s-maxage, private, no-store; never cache personal pages.
CodeMeaning
502Bad or no reply from the backend
503No healthy backend or load shedding
504Backend slower than the proxy timeout

Live updates: polling to WebSocketsLesson 7 →

MethodNotes
Short pollingSimple, wasteful, late
Long pollingQuick, but a request per message
SSEOne-way text/event-stream, auto-reconnect, Last-Event-ID
WebSocketTwo-way; GET with Upgrade, then 101
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# SSE: proxy_buffering off;

Without these, WebSockets fail in prod; buffered SSE shows 0 bytes.

  • Check Origin on the handshake, authenticate with a short-lived ticket, use wss://.
  • Ping/pong heartbeats find dead clients; they also beat idle timeouts (nginx 60 s).
  • Watch bufferedAmount for slow clients. Many servers need Redis pub/sub. 10,000 idle sockets took about 95 MB.

Debug with curl, ss and tcpdumpLesson 8 →

curl -s -o /dev/null URL -w '
dns   %{time_namelookup}
tcp   %{time_connect}
tls   %{time_appconnect}
ttfb  %{time_starttransfer}
total %{time_total}
'

Values are cumulative; subtract to get each step. Run 5 to 10 times.

curl exitLayer
6DNS: could not resolve
7Connect: refused or blocked
28Timeout
35 / 60TLS handshake / certificate
22HTTP error with -f
ss -ltnp
Who listens, on which address
nc -zv HOST PORT
Cleanest port test
curl -v URL
> sent, < received
tcpdump -nn -i any 'host X'
Did the SYN leave or arrive?
openssl s_client -connect H:443
Chain, dates, Verify return code

Symptom to causeLesson 8 →

SymptomFirst check
Could not resolve hostdig NAME, /etc/resolv.conf
Network unreachableip route: no default route
Connection refusedss -ltnp: service up? bound to 127.0.0.1?
Hang, then ETIMEDOUTSecurity group or firewall; tcpdump
ECONNRESET / socket hang upKeep-alive timeouts, who sent the RST
Fails for some usersOne bad backend, stale DNS, IPv6, MTU
Works on Wi-Fi, fails on VPNMTU: ping -M do -s 1400 HOST

Tip: Ping failing proves little (ICMP is often blocked). Capture at both ends and keep the output; treat captures as sensitive.

Interview one-linersLesson 0 →

QuestionShort answer
MAC vs IP?MAC is the next hop and changes per hop. IP is the final stop.
Refused vs timed out?Refused: nothing listens. Timed out: packets dropped.
Flow vs congestion control?Receiver's window vs the sender's own window.
Changed A record, still old IP?Resolvers cache until the TTL runs out.
HTTP/2 vs HTTP/3?HTTP/2 still has TCP head-of-line blocking; HTTP/3 does not.
Works in browser, fails in Node?Missing intermediate certificate.
SSE vs WebSocket?SSE: one-way, plain HTTP. WebSocket: two-way, more to build.

A cheat sheet is a reminder, not a teacher. Each card links to the lesson that explains it step by step.