Workbench / Volume 1 Exercises: Foundations of Computing
V1·09
Networking Fundamentals
Exercises for Volume 1, chapter 09: layers and the OSI and TCP/IP models, Ethernet and MAC addresses, IPv4 and IPv6, subnetting and CIDR, routing, NAT, ARP and neighbour discovery, ICMP, DHCP, ports and sockets, UDP, TCP (handshake, sequence numbers, retransmission, flow and congestion control, teardown and TIME_WAIT), DNS (hierarchy, resolvers, records, TTL, security), TLS (cryptography, certificates, the TLS 1.3 handshake, forward secrecy) and the sockets API with timeouts. 13 theory questions, 12 programming exercises, 3 cumulative projects with chapters 01–08, the concepts the chapter leaves out, and 6 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. The programming exercises run on loopback (127.0.0.1), so you need no second machine: Java servers and clients, tcpdump, ss, openssl and curl. The outputs in the solutions come from this book's sandbox (Linux 6.18, Java 21). Two warnings that are themselves lessons:
- The sandbox sits behind a transparent proxy: an outbound TCP connection to any address "succeeds" (P4), and its DNS resolver answers only for allowlisted names (P10). Corporate networks, Kubernetes service meshes and some Wi-Fi networks behave the same way, so "connect succeeded" doesn't always mean what you think.
- Loopback has almost no latency, so some effects are tiny here and large across real networks. The solutions say when.
Coverage map.
| Chapter component | Exercises |
|---|---|
| layers; OSI and TCP/IP models; encapsulation | T1 |
| Ethernet, MAC addresses, ARP and neighbour discovery | T2 |
| IPv4, IPv6, subnetting and CIDR | T3, P1 |
| routing, NAT, ICMP, DHCP | T4 |
| ports, sockets, the sockets API | T5, P2 |
| UDP | T6, P3 |
| TCP: handshake, sequence numbers, ACKs, retransmission | T7, P5 |
| flow control; congestion control | T8, P7 |
| Nagle's algorithm and delayed ACKs (sockets in practice) | T8, P6 |
| teardown and TIME_WAIT | T9, P8 |
| DNS: hierarchy, resolvers, records, TTL and caching, operations and security | T10, P10 |
| TLS: symmetric/asymmetric crypto, certificates and CAs, TLS 1.3 handshake, forward secrecy, TLS per language | T11, T12, P11 |
| timeouts and the fallacies of distributed computing | T13, P4, P12 |
Theory
T1. Layers and encapsulation
- List the TCP/IP layers and map OSI's seven layers onto them. For each layer, name the unit (frame, packet, segment, message) and the address it uses.
- Your Java service sends a 300-byte JSON response over HTTPS to a phone on Wi-Fi. Describe the headers added at each layer on the way down, roughly how many bytes each adds, and which devices on the path read which layers.
- Why are layers useful, and give one real case where they leak (a lower layer's behaviour shows through to the application).
T2. Ethernet, MAC addresses and ARP
- What is a MAC address, what's its scope, and why does a packet keep its IP addresses end to end but change MAC addresses at every hop?
- Walk through ARP when your laptop (192.168.1.20/24) sends its first packet to 8.8.8.8. What does IPv6 use instead?
- What does a switch do differently from a hub and from a router? What's a VLAN, and what's the cloud equivalent?
T3. Addresses, subnets and CIDR
- For
10.20.0.0/16, give the netmask, the number of addresses, and the first and last usable addresses. How many /24 subnets does it contain? - You're designing a cloud network (VPC) for TiffinBox in
10.20.0.0/16across 3 availability zones, each with a public subnet (load balancers, NAT), a private application subnet (up to 2,000 containers) and a private database subnet. Choose subnet sizes and write the CIDR blocks. (Cloud providers reserve 5 addresses per subnet in AWS.) - What are private address ranges (RFC 1918), and why do overlapping ranges cause pain when two companies merge or you peer VPCs?
- How is IPv6 different (address size, notation, typical subnet size, no NAT needed), and why is IPv6 adoption still partial?
T4. Routing, NAT, ICMP and DHCP
- How does a router choose where to send a packet (longest prefix match)? Given routes 10.0.0.0/8 → A, 10.20.0.0/16 → B, 0.0.0.0/0 → C, where do 10.20.5.9, 10.99.1.1 and 8.8.8.8 go?
- Explain how NAT lets 50 devices at home share one public IP, what table it keeps, and three problems it causes for applications (inbound connections, idle timeouts, logging and rate limiting by IP).
- What are ICMP "destination unreachable", "time exceeded" and "fragmentation needed" used for? How does
traceroutework? Why is blocking all ICMP a bad idea? - What does DHCP give a device, and what goes wrong when the DHCP server hands out a wrong DNS server or gateway?
T5. Ports and sockets
- What identifies a TCP connection? Why can a server on port 443 have 100,000 simultaneous connections, while a single client machine connecting to one server address and port is limited to about 28,000?
- Describe the server-side and client-side socket call sequences (socket, bind, listen, accept, connect, read/write, close). What is the listen backlog, and what happens when it's full?
- Why does binding to 127.0.0.1 versus 0.0.0.0 matter for a service in a container?
T6. UDP
- What does UDP provide and not provide compared with TCP? Using P3, what happens to message boundaries, an oversized datagram, and a datagram larger than the receiving buffer?
- Name four protocols built on UDP and say why each chose it.
- Why is QUIC (HTTP/3) built on UDP instead of being a new transport protocol, and what does it put back that UDP lacks?
T7. TCP: handshake, sequence numbers and retransmission
- Using P5's
tcpdumpoutput, explain each packet: SYN, SYN-ACK, ACK, the request, its ACK, the response, its ACK, and the FIN exchange. What do theseqandacknumbers mean, and why does each side choose a random initial sequence number? - Why does TCP being a byte stream mean an application must frame its own messages? P5's server read three 8-byte writes as one 24-byte read: how would you parse orders from such a stream?
- How does TCP detect and recover from loss (retransmission timeout, duplicate ACKs/fast retransmit, SACK)? What does a single lost packet do to an HTTP/2 connection carrying 20 requests?
T8. Flow control, congestion control, Nagle and delayed ACKs
- Distinguish flow control from congestion control. What does each protect, and what signals does each use?
- The bandwidth-delay product: how much data must be "in flight" to fill a 1 Gbit/s link with a 100 ms round trip? What happens if the receive window is 64 KB?
- Compare loss-based (Reno, CUBIC) and model-based (BBR) congestion control. This sandbox uses
bbr; most Linux servers default to CUBIC. - P6: two small writes followed by a read took 43 ms per round with Nagle's algorithm on and 0.06 ms with
TCP_NODELAY. Java's built-inHttpServershowed the same: 44 ms per request on a reused connection, 1.5 ms withsun.net.httpserver.nodelay=true. Explain the interaction between Nagle's algorithm and delayed ACKs.
T9. Closing connections and TIME_WAIT
- Explain the FIN/ACK exchange, half-close, and the difference between a FIN and an RST. When does a peer receive "connection reset by peer"?
- What is TIME_WAIT, which side enters it, how long does it last, and why does it exist? P8 opened and closed 1,000 connections: 1,000 TIME_WAIT sockets appeared on the side that closed first.
- A service that makes an HTTP call per request without connection reuse starts failing at high load with "Cannot assign requested address". Explain using T5 and this question, and give the real fix.
- What does CLOSE_WAIT in
ssmean, and what bug does a growing number of CLOSE_WAIT sockets indicate?
T10. DNS
- Walk through resolving
api.tiffinbox.infrom a cold cache: stub resolver, recursive resolver, root,.inTLD and authoritative servers. Where is each answer cached, and for how long? - Explain A, AAAA, CNAME, MX, TXT, NS, SRV and CAA records with a real use for each.
- You're migrating
api.tiffinbox.into a new load balancer IP. The record's TTL is 86,400 s. Plan the change so clients switch within minutes, and explain why some clients will still hit the old IP for longer (including the JVM's own DNS cache). - Name three DNS-related security or operational problems (spoofing/cache poisoning, DNSSEC, DNS over HTTPS/TLS, dangling CNAMEs and subdomain takeover, DNS as a single point of failure).
T11. TLS: the cryptography
- What three guarantees does TLS give (and what doesn't it hide)?
- Explain why TLS uses both asymmetric cryptography (key exchange, signatures) and symmetric cryptography (AES-GCM, ChaCha20-Poly1305) for the bulk data.
- Walk through the TLS 1.3 handshake (ClientHello with key share, ServerHello, certificate, CertificateVerify, Finished). How many round trips does it take before the client can send its HTTP request, and what does 0-RTT resumption add and risk?
- What is forward secrecy, and why does an ephemeral (EC)DHE key exchange provide it while old RSA key exchange didn't?
T12. Certificates and trust
- Explain a certificate chain (leaf, intermediate, root), what the client checks (signatures up to a trusted root, validity dates, hostname against the SAN, key usage, revocation), and where the trusted roots come from.
- P11's three errors: "unable to find valid certification path to requested target", success with our CA trusted, and "No subject alternative names matching IP address 127.0.0.1 found". Explain each, and why "fixing" the first with a trust-all
TrustManageris dangerous. - Certificates expire. Why have lifetimes shrunk (to 398 days, and moving towards 47 days by 2029), and what has to be in place so expiry never causes an outage?
- What's mutual TLS, and where is it used?
T13. Timeouts and the fallacies of distributed computing
- List the eight fallacies of distributed computing and give, for four of them, a bug they cause in ordinary service code.
- Name the timeouts a robust HTTP client needs (DNS, connect, TLS handshake, request/response, idle in pool) and what happens if each is missing. P4 showed a connect to a closed port failing in 1.5 ms; what does a missing connect timeout do when the host is down and packets are silently dropped?
- A request from Hyderabad to a server in Virginia has a ~200 ms round trip. How long, at minimum, does a fresh HTTPS request take (DNS cached), and what are three ways to reduce it?
Programming exercises
P1. A subnet calculator
Write a Java Cidr record with parse("10.20.16.0/20"), contains(String ip), size(), first() and last() (as strings), overlaps(Cidr other), and split(int newPrefix) returning the subnets. Use it to check T3's VPC plan: every subnet lies inside the VPC, no two overlap, and each is aligned to its size. Reuse chapter 06's IP-to-integer code.
P2. A TCP server, a client and a protocol
Write a line-based TCP server in Java (port 9000) that accepts commands ORDER <dish> <qty>, STATUS <id> and QUIT, replying with one line each, handling each connection on a virtual thread. Write a client that sends commands and reads replies. Test with nc localhost 9000 too. Then make the client send three commands in a single write and the server still answer all three correctly.
P3. UDP's behaviour
Bind a DatagramSocket on loopback and, from another socket: send three 8-byte messages and receive them; try to send 70,000 bytes; send 50 bytes into a 10-byte receive buffer. Then simulate loss: write a UDP "ping" client that sends 100 numbered datagrams to an echo server which drops 10% at random, and report which were lost and the round-trip time of the rest.
P4. Connection failures and timeouts
From Java, connect to (a) a closed port on localhost, (b) a non-routable address (10.255.255.1:80) with a 2-second connect timeout, and (c) a server that accepts but never responds, with a 1-second read timeout (setSoTimeout). Print the exception and elapsed time for each. Then use Java's HttpClient against the silent server with and without .timeout(Duration.ofSeconds(2)) on the request.
P5. Watch a TCP connection
Run sudo tcpdump -i lo -n 'tcp port 9102' in one terminal; in another, run a tiny server and client (any language) that connect, send an 18-byte request, reply with 19 bytes, and close. Annotate every line of the capture: flags, sequence and acknowledgement numbers, lengths. Then repeat with the client sending three separate small writes and observe how many segments appear.
P6. Nagle meets delayed ACK
Write a client and server on loopback where the client does write 100 bytes, write 100 bytes, read 1 byte 50 times, and the server reads 200 bytes then writes 1 byte. Time it with setTcpNoDelay(false) and true on the client. Then start Java's built-in com.sun.net.httpserver.HttpServer and measure 100 requests over one reused HttpClient connection, with and without -Dsun.net.httpserver.nodelay=true.
P7. See flow control
Write a server that accepts a connection and reads only 1 KB per second. Write a client that writes 10 MB as fast as it can, printing how many bytes it has written every second. Watch ss -tni (Recv-Q on the server socket, Send-Q on the client, and the window) while it runs. Then set small socket buffers (setReceiveBufferSize(4096) on the server before binding, setSendBufferSize(4096) on the client) and compare how soon the client blocks.
P8. TIME_WAIT and port exhaustion
Open and close 1,000 short TCP connections to a local server, with the client closing first, and count sockets in TIME_WAIT before and after with ss -tan state time-wait. Then make the server close first and count again: whose ports are held? Compute how many connections per second a client could sustain to one server before running out of ephemeral ports. Finally, do the same work with one persistent connection.
P9. Measure the cost of connection setup
Against a local HTTP server, measure the time per request for (a) a new TCP connection per request (Connection: close), (b) a reused keep-alive connection (with TCP_NODELAY on the server, P6), and (c) HTTPS with a new connection per request vs a reused one (use P11's server). Then extrapolate to a 200 ms round trip using T13's round-trip counting.
P10. A DNS client by hand
Build a DNS query for an A record in Java (12-byte header with ID, flags with recursion desired, one question; the name as length-prefixed labels; type 1, class 1), send it over UDP to a resolver on port 53, and parse the response: response code, answer count, and each answer's type, TTL and address, following compression pointers. Run it twice and watch the TTL count down. Compare with InetAddress.getAllByName timing on first and second calls.
P11. TLS from a self-made CA
With openssl, create a test CA and a server certificate for api.tiffinbox.test with SANs api.tiffinbox.test and localhost, signed by the CA; verify the chain with openssl verify. Package the server key and chain as PKCS#12, start a Java HttpsServer with it, and connect with Java's HttpClient: (a) with the default trust store, (b) with a trust store containing your CA, (c) by IP address. Print the protocol and cipher suite and time the first and second requests.
P12. A resilient HTTP call
Write a Java method fetchMenu(kitchenId) that calls a flaky local HTTP server (which randomly delays 0–3 s, returns 503 20% of the time, or closes the connection mid-response 5% of the time). Use one shared HttpClient with a connect timeout, a per-attempt request timeout of 800 ms, an overall deadline of 2.5 s, up to 3 attempts with exponential back-off and jitter, retrying only on timeouts, connection errors and 503. Report the success rate and latency percentiles over 1,000 calls, with and without retries.
Cumulative projects (chapters so far: 01–08)
C1. A tiny HTTP/1.1 server from sockets
Implement an HTTP/1.1 server in Java directly on ServerSocket (no frameworks): parse the request line and headers (CRLF framing, case-insensitive header names), support GET for static files from a directory and POST /orders with a JSON body read by Content-Length, persistent connections (keep-alive by default, Connection: close honoured), correct Content-Type, Content-Length and status codes (200, 400, 404, 405, 413, 500), path-traversal protection, an idle timeout, limits on header size and body size, and one virtual thread per connection. Test with curl -v, a browser, and a script that sends malformed requests.
Combines: streams and exit codes (ch 01); parsing, errors and tests (ch 02); maps for headers (ch 03); linear parsing (ch 04); boundary cases (ch 05); bytes vs characters, UTF-8, lengths (ch 06); buffering and syscalls (ch 07, 08); TCP framing, keep-alive, Nagle and timeouts (ch 09).
C2. A latency-injecting TCP proxy
Write a TCP proxy in Java that listens on one port and forwards bytes to a target host and port in both directions, adding a configurable one-way delay (e.g. 50 ms) to each chunk, an optional bandwidth limit (bytes per second), and an optional random connection reset rate. Use it to reproduce, on one laptop, the effects of real networks: run P9's measurements and P12's resilient client through it, and measure how connection reuse, Nagle (P6) and TLS handshakes behave at 100 ms RTT.
Combines: CLI arguments and exit codes (ch 01); clean concurrency code (ch 02); queues with timestamps (ch 03); scheduling (ch 04); rate and probability (ch 05); byte handling (ch 06); threads and virtual threads (ch 08); TCP streams, half-close, resets, RTT and bandwidth-delay (ch 09).
C3. Diagnose "the API is slow from India"
TiffinBox's API is hosted in one region (Virginia, us-east-1). Users in Hyderabad report the app is slow: each screen makes 6 sequential API calls, each a fresh HTTPS connection (the mobile app creates a new client per call), returning 5–40 KB of uncompressed JSON. Using chapters 01–09, estimate the current screen load time, list the causes in order of impact, propose fixes with estimated gains, and write a measurement plan (what to collect from real devices and servers to confirm).
Combines: measuring (ch 01); client code design (ch 02); payload structures (ch 03); sequential vs parallel calls (ch 04); percentiles over real networks (ch 05); payload sizes and compression (ch 06); latency numbers (ch 07); connection and descriptor costs (ch 08); round trips, handshakes, TCP slow start, CDNs (ch 09).
What the chapter leaves out
HTTP/2, HTTP/3 and head-of-line blocking
HTTP/1.1 sends one request at a time per connection (pipelining never worked in practice), so browsers open ~6 connections per host. HTTP/2 multiplexes many request streams over one TCP connection with binary framing and header compression (HPACK), which removed the need for those parallel connections and for hacks like domain sharding and sprite sheets, but a single lost TCP packet stalls every stream (T7). HTTP/3 runs the same semantics over QUIC (T6): independent streams, a combined transport+TLS handshake, 0-RTT resumption, connection migration. Practical consequences: enable HTTP/2 between clients and your edge and between services where supported (gRPC requires it); HTTP/3 is mostly an edge/CDN concern today; and because HTTP/2 uses few connections, a load balancer balancing connections can leave backends uneven (balance per request: gaps below).
Load balancers, proxies and what they hide
Real requests pass through L4 load balancers (forwarding TCP/UDP by connection, e.g. AWS NLB) and L7 proxies (terminating TLS and HTTP: ALB, nginx, Envoy, service-mesh sidecars). Consequences: the server sees the proxy's IP, so the client's address arrives in X-Forwarded-For or the PROXY protocol (and must be trusted only from your proxies); TLS may terminate at the edge, so traffic behind it is plain HTTP unless re-encrypted; idle timeouts at each hop must be ordered (client < load balancer < server keep-alive, or you get intermittent 502s when the server closes a connection the proxy is about to reuse); health checks decide which backends get traffic; connection-level balancing with long-lived HTTP/2 or gRPC connections needs per-request balancing or periodic reconnection. The sandbox proxy in P4 is a reminder that a successful connect can be to a middlebox.
MTU and path MTU black holes
Each link has a maximum transmission unit (1,500 bytes on Ethernet; less over VPNs, tunnels and some mobile networks; 9,001 "jumbo frames" inside some cloud networks). TCP picks a maximum segment size from the MTU, and path MTU discovery relies on ICMP "packet too big" messages. When a firewall drops those ICMP messages (T4) and a tunnel lowers the MTU, small packets (handshakes, small requests) work while large ones vanish: SSH logs in but ls of a big directory hangs; HTTPS handshakes complete but large responses never arrive. Diagnosis: ping -M do -s 1472 host style probes, tracepath; fixes: allow ICMP, clamp MSS on tunnels, lower the MTU on VPN interfaces.
Network debugging toolkit
Know these by heart: curl -v and curl -w '%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer} %{time_total}\n' (splits a request's latency into DNS, TCP, TLS, server and transfer); dig +trace and dig @resolver (DNS); openssl s_client -connect host:443 -servername host (certificates and TLS); ss -tanp and ss -tni (sockets, states, windows, RTT estimates); tcpdump/Wireshark (packets); mtr (traceroute with loss per hop); nc (raw TCP/UDP); ip addr, ip route, ip neigh (addresses, routes, ARP). In Kubernetes, kubectl exec into a debug container (nicolaka/netshoot) to run them from the pod's network namespace.
DNS inside Kubernetes and service discovery
In Kubernetes, pods resolve service names through cluster DNS (CoreDNS) with a search list (<ns>.svc.cluster.local, svc.cluster.local, …) and ndots:5: any name with fewer than five dots is first tried with each search suffix, so api.example.com can cause four or more failed queries before the real one, multiplied across every lookup. Use fully qualified names with a trailing dot or lower ndots for external-heavy workloads, and cache. Service discovery more broadly (Consul, Eureka, Kubernetes Services, mesh control planes) replaces DNS TTL tricks with registries and health-checked endpoint lists; clients that resolve once and pin connections forever (T10) miss scale-ups and failovers.
Certificate pinning and the operational cost of TLS
Mobile apps sometimes pin the expected certificate or public key to resist interception, but a rotated key or a changed CA then bricks every installed app version until users update; pin intermediate or backup keys, or prefer Certificate Transparency monitoring over pinning. Other operational realities: corporate TLS-inspecting proxies re-sign traffic with their own CA (Java trust stores need it; pinned apps break); expired intermediates in old trust stores (old Android versions); clock skew on devices making valid certificates "not yet valid"; and the move to post-quantum key exchange (larger ClientHellos that some middleboxes mishandle). Treat TLS configuration as code with tests and expiry monitoring.
Senior exercises
S1. Intermittent 502s after a deploy
After moving a Java service behind a new L7 load balancer (idle timeout 60 s), about 0.1% of requests fail with 502, randomly, mostly in the morning after quiet nights, never in load tests. The service is Tomcat with a keep-alive timeout of 20 s. Explain the most likely cause using TCP connection lifecycles, how to prove it, and the fix. Name two other causes you'd rule out.
S2. Design the network for a new service
TiffinBox's new payments service must be reachable only by the order service, call a payment gateway on the internet, and store data in a managed database. Design the network: subnets, routing (NAT for outbound), security groups/firewall rules, DNS names, TLS/mTLS, timeouts and how you'd verify it's not reachable from anywhere else.
S3. Review an HTTP client wrapper
A shared library wraps Java's HttpClient: it creates HttpClient.newHttpClient() inside each call, sets no timeouts, retries any exception 5 times immediately, disables certificate validation "for internal services", and logs full request bodies at INFO. Write the review, ranked by severity.
S4. Capacity and cost of cross-region traffic
TiffinBox plans a second region (Mumbai) with active-active services that replicate order events to Virginia. Estimate the network requirements and costs: 2,000 orders/minute at peak, each producing 5 events of 2 KB (JSON), replicated both ways; plus 50 GB/day of logs shipped to a central region. Compute bandwidth, the effect of RTT on a synchronous replication design (ack before responding to the user), data-transfer cost at a typical $0.02/GB inter-region rate, and recommend a design.
S5. Make the "it's the network" conversation productive
In an incident channel, an application team says "the network is dropping requests" and the network team says "the network is fine, it's your app". Write the checklist you'd run, in order, to locate the problem in a specific layer within 30 minutes, with the command or metric for each step and what each result would mean.
S6. Teach latency with a physical demonstration
Design a 15-minute session for new engineers that makes round trips tangible: use C2's latency proxy (or curl -w against a far-away server), show the cost of DNS, TCP, TLS and requests, and end with three coding rules. Write the demo script and the rules.