CNComputer Networks

Reference

Networks cheat sheet

Everything you should recall without thinking. Print it (Ctrl/⌘+P — the layout is print-styled).

The subnet table — memorise this one

CIDRMaskBlock sizeAddressesUsable
/24255.255.255.0256256254
/25255.255.255.128128128126
/26255.255.255.192646462
/27255.255.255.224323230
/28255.255.255.240161614
/29255.255.255.248886
/30255.255.255.252442
/23255.255.254.0512512510
/22255.255.252.010241,0241,022
/16255.255.0.065,53665,534
/8255.0.0.016,777,21616,777,214
usable hosts = 2(32−prefix) − 2  (minus network and broadcast)
block size = 256 − (the interesting mask octet)

To find the subnet of an address: compute the block size, count up in block-size steps until you pass the address, step back one. That's the network address; next network − 1 is the broadcast.

VLSM: always allocate largest first — subnets must be aligned to their block size.
Cloud caveat: AWS reserves 5 addresses per subnet, so a /24 gives 251.

Formulas

── DELAY ────────────────────────────────────────────────────────
total delay = propagation + transmission + queueing + processing
propagation = distance / 200,000 km/s   ≈ 5 µs per km in fibre
transmission = packet size / bandwidth
RTT = 2 × one-way latency

── THROUGHPUT ───────────────────────────────────────────────────
BDP (bandwidth-delay product) = bandwidth × RTT
   → the window size needed to keep the pipe full
max throughput ≈ window size / RTT

  1 Gbps × 100 ms = 12.5 MB BDP
  with a 64 KB window → 655 KB/s ≈ 5 Mbps   # 0.5% of the link!
  → hence the WINDOW SCALE option (up to ~1 GB windows)

── MTU / MSS ────────────────────────────────────────────────────
MSS = MTU − IP header − TCP header = 1500 − 20 − 20 = 1460
IPv6: 1500 − 40 − 20 = 1440
Header overhead per full frame: 14 + 20 + 20 + 4 = 58 bytes

── HANDSHAKE COSTS (round trips before data) ────────────────────
DNS (cold)          1+ RTT
TCP handshake       1 RTT
TLS 1.2             2 RTT       TLS 1.3    1 RTT     TLS 1.3 resumed  0
QUIC (HTTP/3)       1 RTT total (transport + crypto merged), 0 resumed
  → cold HTTPS ≈ 3 RTT before the request is sent.
    At 150 ms RTT that is ~450 ms of nothing.

── CONGESTION ───────────────────────────────────────────────────
slow start           cwnd doubles each RTT (exponential)
congestion avoidance cwnd += 1 MSS per RTT (linear)
3 duplicate ACKs     cwnd /= 2, fast recovery
timeout              cwnd = 1, restart slow start
effective window     = min(receive window, congestion window)

Ports & header sizes

Ports worth knowing
20/21  FTP data / control
22     SSH, SFTP
23     Telnet
25     SMTP (server↔server)
53     DNS (UDP, TCP if large)
67/68  DHCP server / client
80     HTTP
110    POP3      995 POP3S
123    NTP (UDP)
143    IMAP      993 IMAPS
179    BGP (over TCP)
389    LDAP      636 LDAPS
443    HTTPS, QUIC/HTTP-3 (UDP)
587    SMTP submission
3306   MySQL
5432   PostgreSQL
6379   Redis
8080   HTTP alternate
9092   Kafka
27017  MongoDB

0–1023      well known
1024–49151  registered
49152–65535 ephemeral
Header sizes & ranges
Ethernet header      14 B (+4 CRC)
IPv4 header          20 B min, 60 max
IPv6 header          40 B fixed
TCP header           20 B min, 60 max
UDP header            8 B
Ethernet MTU       1500 B
Jumbo frame        9000 B
TCP window field     16 bits → 64 KB
  with window scale  up to ~1 GB
Port number         16 bits → 65,535
IPv4 address        32 bits → 4.3 × 10⁹
IPv6 address       128 bits → 3.4 × 10³⁸
MAC address         48 bits
TTL typical      64 (Linux), 128 (Windows)
VLAN ID             12 bits → 4,094 usable
Special IPv4 rangeMeaning
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16Private (RFC 1918)
127.0.0.0/8Loopback
169.254.0.0/16DHCP failed (link-local); also cloud metadata at .169.254
224.0.0.0/4Multicast
0.0.0.0/0Default route / any address

TCP states & flags

StateMeansMany of them means
LISTENAwaiting connectionsNormal for a server
SYN_SENTSent SYN, no replyCan't reach the server — filtered or wrong port
SYN_RCVDHalf-openPossible SYN flood
ESTABLISHEDOpenNormal
FIN_WAIT_1/2We closed, waiting on the peerThe peer is leaking connections
CLOSE_WAITPeer closed, we haven'tYour app isn't calling close()
TIME_WAITWaiting 2×MSL (~60 s)Normal on the closer; excessive ⇒ port exhaustion — reuse connections
Flags   SYN open · ACK acknowledge · FIN graceful close
        RST abort (discards data) · PSH deliver now · URG unused

Open   SYN → SYN-ACK → ACK                        (3, piggybacked)
Close  FIN → ACK → FIN → ACK                      (4, full duplex)

TIME_WAIT exists to (1) re-ACK a retransmitted FIN if the last ACK was
lost, and (2) let stray duplicates expire before the 4-tuple is reused.

HTTP codes & headers

Status codes
2xx  200 OK      201 Created
     204 No Content  206 Partial
3xx  301 Moved Permanently (cached!)
     302 Found    307 Temporary (keeps method)
     304 Not Modified
     308 Permanent (keeps method)
4xx  400 Bad Request
     401 Unauthenticated
     403 Forbidden (authenticated)
     404 Not Found  409 Conflict
     422 Unprocessable
     429 Too Many Requests
5xx  500 Internal  502 Bad Gateway
     503 Unavailable (retry)
     504 Gateway Timeout
Headers that matter
Cache-Control  max-age, no-cache,
               no-store, private, immutable
ETag / If-None-Match  → 304
Vary           cache key per header
Content-Encoding gzip, br
Authorization  Bearer / Basic
Set-Cookie     HttpOnly; Secure;
               SameSite=Lax
Access-Control-Allow-Origin (CORS)
Strict-Transport-Security (HSTS)
Content-Security-Policy
X-Content-Type-Options: nosniff
Retry-After    with 429 / 503
Upgrade: websocket → 101
MethodSafeIdempotentCacheable
GET / HEADYesYesYes
PUT / DELETENoYesNo
POSTNoNoRarely
PATCHNoDepends on the patchNo

DNS records

TypeMapsGotcha
A / AAAAName → IPv4 / IPv6
CNAMEName → nameNot allowed at the zone apex
MXDomain → mail serverLower priority number wins
NSZone → name serversHow delegation works
TXTFree textSPF, DKIM, DMARC, verification
SOAZone metadataHolds the negative-cache TTL
PTRIP → nameMail servers check it
SRVService → host:portService discovery
CAAWhich CAs may issueDefence against mis-issuance
TTL discipline

Lower to 60 s a day before a migration, change, verify, raise again. And remember DNS is not reliable failover — resolvers and browsers sometimes ignore short TTLs. Use anycast or health-checked load balancers for that.

The distinction table

PairThe one difference
TCP / UDPGuarantees vs overhead; byte stream vs datagram
Bandwidth / latencyLanes vs length
Flow / congestion controlProtects the receiver / the network
Switch / routerL2 MAC / L3 IP — only the router stops broadcasts
MAC / IPPer-hop, rewritten / end-to-end, unchanged
Routing / forwardingBuild the table / use it
Distance vector / link stateTrust neighbours / know the map
IGP / EGPOSPF inside / BGP between
NAT / firewallRewriting / policy. NAT is not security.
Recursive / iterative DNSResolver works for you / referrals
301 / 302Permanent and cached / temporary
401 / 403Not authenticated / not permitted
Symmetric / asymmetricFast / solves key distribution
Hash / MAC / signatureIntegrity / +auth / +non-repudiation
TLS 1.2 / 1.32 RTT, optional FS / 1 RTT, mandatory FS
MTU / MSSFrame payload / TCP payload
FIN / RSTGraceful / abort
WebSocket / SSEBidirectional / server→client, plain HTTP
no-cache / no-storeRevalidate / never store
CSMA/CD / CSMA/CADetect (wired) / avoid (radio can't listen while sending)

Commands

── WHERE IS THE TIME GOING? (the single best command) ───────────
$ curl -w 'dns:%{time_namelookup} tcp:%{time_connect} tls:%{time_appconnect} ttfb:%{time_starttransfer} total:%{time_total}\n' -o /dev/null -s https://example.com

── DNS ──────────────────────────────────────────────────────────
$ dig +short example.com        # just the answer
$ dig +trace example.com        # the full delegation walk
$ dig @8.8.8.8 example.com      # bypass the local resolver
$ dig -x 8.8.8.8                # reverse lookup
$ dig example.com MX +short

── CONNECTIVITY ─────────────────────────────────────────────────
$ ping -c 4 host                # ICMP — often filtered, not proof
$ nc -zv host 443               # refused = closed; timeout = filtered
$ traceroute host  /  tracepath host
$ traceroute -T -p 443 host     # TCP-based, when ICMP is blocked
$ mtr -rwc 100 host             # continuous — finds flaky hops
$ ping -M do -s 1472 host       # MTU probe (1472 + 28 = 1500)

── SOCKETS & ROUTES ─────────────────────────────────────────────
$ ss -tanp                      # sockets, states, owning process
$ ss -ti                        # cwnd, rtt, retransmits
$ ss -tan | awk '{print $1}' | sort | uniq -c   # state histogram
$ ip addr / ip route / ip neigh # addresses, routes, ARP cache
$ ip route get 8.8.8.8          # which route WOULD be used

── HTTP & TLS ───────────────────────────────────────────────────
$ curl -v https://host          # DNS, TCP, TLS, headers, all of it
$ curl -I https://host          # headers only
$ curl --http1.1 / --http2 / --http3
$ openssl s_client -connect host:443 -servername host < /dev/null
$ openssl x509 -in cert.pem -noout -text -dates

── PACKETS ──────────────────────────────────────────────────────
$ tcpdump -ni any 'tcp port 443'
$ tcpdump -ni any 'tcp[tcpflags] & tcp-rst != 0'   # who resets
$ tcpdump -ni any 'icmp'        # is PMTUD being blocked?
$ tcpdump -w cap.pcap host x    # capture, open in Wireshark

Decision trees

TCP or UDP?

Is late data still useful?
├─ NO  (voice, video, game state, live telemetry) → UDP
└─ YES → do you need ordering and completeness?
         ├─ YES → TCP (or QUIC for many parallel streams)
         └─ NO, and the message is small + idempotent → UDP (DNS-shaped)

Real-time transport for a web app

Which direction does data flow?
├─ server → client only  → SSE (plain HTTP, auto-reconnect, Last-Event-ID)
├─ both directions       → WebSocket (wss:// only)
└─ many parallel streams + lossy mobile networks → HTTP/3 / QUIC

"The site is slow" — where to look

Run the curl timing command. Then:
  time_namelookup high    → DNS. Check TTLs and the resolver.
  time_connect high       → network RTT or a saturated path. traceroute/mtr.
  time_appconnect high    → TLS. Check version, chain length, OCSP.
  time_starttransfer high → the SERVER is slow. Not a network problem.
  total >> starttransfer  → bandwidth or window. Check BDP and ss -ti.

"I can't reach it"

Does the name resolve?           → no  → DNS
Does `nc -zv host port` connect? → refused → reachable, nothing listening
                                 → timeout  → filtered (firewall/security group)
Connects but TLS fails?          → cert hostname, dates (clock!), chain
Works small, hangs large?        → MTU / PMTUD (ICMP blocked)
Server logs 200, browser blocks? → CORS
The three sentences to leave with

1. Each layer guarantees something and pushes the rest upward — know where each guarantee stops.
2. MAC addresses change every hop; IP addresses don't.
3. Bandwidth is capacity, latency is delay, and most "slow" problems are round trips rather than throughput.