Skip to contents
OpenLearningTHE STUDY LIBRARY

In depth study guide · Edition 2026.12

Computer networks, explained from the packet up

A practical foundation with diagrams, calculations, local labs, and complete answers

A substantial original guide to local links, addressing, routing, DNS, transports, TLS, HTTP, socket programming, performance, and troubleshooting.

14 chapters11 diagrams28 practice tasks

Before you begin

How to use this guide

Learners who can read small programs and want to understand what happens between an application and a network service.

Helpful background

What you will be able to do

A useful study rhythm

Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.

For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.

Scope and assumptions

Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.

Chapter 01

Follow one message through the network

Start with a concrete message, then separate the jobs needed to carry it.

By the end of this chapter
  • Explain packets, protocols, and encapsulation
  • Distinguish application, transport, Internet, and link responsibilities

A network is a set of cooperating promises

Imagine sending the text "next lesson please" from a browser to a learning service. The text is not placed directly onto a wire as a meaningful request. The application encodes a message, the operating system supplies communication services, and the network interface turns bits into signals. Intermediate devices forward units of data according to rules. A protocol is one such set of rules: participants must agree on meaning, format, ordering, and what to do when an event is missing or invalid.

A packet is a bounded unit handled by some network layer. The word is often used loosely, so name the layer when precision matters. An Ethernet frame carries link-layer information; an IP datagram carries network addressing; a TCP segment carries part of a transport byte stream. A user-visible file may travel in many packets. Different packets can be delayed, dropped, duplicated, or delivered out of order. Applications must choose what final result counts as success.

Go deeper: [1] RFC 1122: Internet host communication requirements

Use layers to ask better questions

Four useful responsibilitiesThe application defines meaning, transport connects application endpoints, IP forwards between networks, and a link moves frames to a local next hop.ApplicationHTTP request, JSON body, or your own framed messageTransportTCP byte stream, UDP datagrams, or QUIC streamsInternetIP addressing and forwarding across networksLinkEthernet or Wi-Fi delivery to a local next hop
Four useful responsibilities. The application defines meaning, transport connects application endpoints, IP forwards between networks, and a link moves frames to a local next hop.Scroll horizontally to read the full diagram on a small screen.

Layering is a debugging tool, not a claim that the implementation fits four perfect boxes. If a hostname cannot be resolved, changing the JSON parser is unlikely to help. If TCP connects and the server returns HTTP 403, basic delivery worked and the next question concerns policy or application identity. Every observation narrows the search only as far as the observation supports. A successful ping does not prove that a particular HTTPS endpoint works.

Encoding turns text into bytes python
message = "learn café"
payload = message.encode("utf-8")
print(len(message), len(payload))
print(payload.decode("utf-8"))
Expected result
10 11
learn café

The example counts characters and encoded bytes separately. This matters when a protocol declares a byte length: the receiver must read the declared number of bytes before decoding the text. UTF-8 uses more than one byte for some characters. Packet headers, files, and sockets operate on bytes, while the program often wants strings. Mixing those units can truncate messages even when both machines use the same human language.

Go deeper: [26] Python 3.11 socket reference · [1] RFC 1122: Internet host communication requirements

Keep these ideas

  • Name the layer before interpreting an observation.
  • Protocols define failure handling as well as message formats.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

1.1 · Practice task

A browser receives a valid HTTP 404 response. Which parts of the path definitely worked, and what remains uncertain?

Hint: A response is stronger evidence than a successful local Wi-Fi connection.

Read the worked solution

1.2 · Practice task

Why is the byte length of "learn café" different from its character count, and where would this cause a bug?

Hint: Inspect UTF-8 encoding rather than assuming one character per byte.

Read the worked solution

Chapter 02

Calculate delay, throughput, and queues

Make performance explanations numerical instead of calling every problem "slow Internet".

By the end of this chapter
  • Separate transmission, propagation, queueing, and processing delay
  • Calculate serialization time and bandwidth-delay product

Four delays hide inside one journey

Transmission delay is the time needed to put a packet onto a link. If the packet contains L bits and the link sends R bits per second, the serialization time is L/R seconds. Propagation delay is the time the signal takes to travel through the medium. Processing delay includes work such as inspecting headers. Queueing delay is waiting behind other traffic. These quantities can coexist: a packet may wait much longer for its turn than it takes to transmit.

Throughput is the useful data rate actually achieved over an interval. Link capacity is only an upper bound on that rate. Protocol headers, acknowledgments, loss recovery, application pauses, and competing traffic consume time or bandwidth. A fast local Wi-Fi connection cannot remove a slow distant bottleneck. Latency is elapsed delay for an operation; bandwidth is capacity per time. Increasing one does not automatically improve the other.

Worked example · A 1,500-byte packet on a 10-Mbit/s link

  1. Convert bytes to bits: 1,500 × 8 = 12,000 bits.
  2. Divide by 10,000,000 bits per second: 0.0012 seconds.
  3. Convert seconds to milliseconds: 1.2 ms. Add propagation, queueing, and processing separately; the 1.2 ms is only serialization.

Result: A packet can have a small transmission time and still experience a large end-to-end delay.

Go deeper: [32] MIT Computer System Engineering, Spring 2018

How much data must be in flight?

Round-trip time, or RTT, measures a trip to another endpoint and back for a particular exchange. A sender that waits for an acknowledgment after every tiny chunk can spend most of its time idle. The bandwidth-delay product estimates the data volume needed in flight to fill a path: rate multiplied by RTT. It is a model, not a guaranteed buffer size. Available capacity, congestion control, receive windows, and changing paths affect the real result.

A packet can wait before it movesThe total observation includes a sender queue, serialization on the bottleneck link, propagation, and receiver processing; measuring only the link rate misses waiting.Sender queueWait for earlier packetsBottleneck linkSpend L/R seconds transmittingPathSignals propagate and routers forwardReceiverProcess the request and form a reply
A packet can wait before it moves. The total observation includes a sender queue, serialization on the bottleneck link, propagation, and receiver processing; measuring only the link rate misses waiting.Scroll horizontally to read the full diagram on a small screen.
Keep the units visible python
rate_bits_per_second = 100_000_000
rtt_seconds = 0.040
in_flight_bytes = rate_bits_per_second * rtt_seconds / 8
print(int(in_flight_bytes))
Expected result
500000

A 100-Mbit/s path with 40-ms RTT has a nominal product of 500,000 bytes. A single 1,000-byte request is nowhere near that volume, so its completion is often dominated by round trips and server work rather than transfer capacity. Conversely, a large download needs enough in-flight data to sustain throughput. Before optimizing, state which workload you mean: a small interactive request and a multi-gigabyte transfer are different experiments.

Go deeper: [18] RFC 5681: TCP congestion control · [32] MIT Computer System Engineering, Spring 2018

Keep these ideas

  • Write units next to every performance number.
  • Tail latency and queueing deserve separate attention.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

2.1 · Practice task

A 2,000-byte message crosses a 2-Mbit/s bottleneck with no other overhead. Calculate serialization delay.

Hint: Multiply bytes by eight, then divide by bits per second.

Read the worked solution

2.2 · Practice task

A service has 20-ms median latency but 800-ms p99 latency. Why might adding link bandwidth fail to help?

Hint: The slowest requests can be waiting for a shared resource.

Read the worked solution

Chapter 04

Read IPv4, IPv6, and CIDR without guessing

Use prefix lengths to reason about address ranges and route matches.

By the end of this chapter
  • Calculate a small IPv4 subnet
  • Recognize IPv6 representation and loopback

An address belongs to an interface context

An IPv4 address contains 32 bits. Dotted decimal is a convenient way to write four groups of eight bits, not four unrelated numbers. CIDR writes a prefix length after a slash. In 192.0.2.64/26, the first 26 bits identify the prefix and the remaining six bits vary, giving 64 addresses. A subnet describes an address range; it does not by itself grant permission to communicate. Routing and policy still matter.

A conventional broadcast-capable IPv4 /26 subnet reserves the all-zero host value as the network address and the all-one host value as the broadcast address. That leaves 62 ordinary host addresses. Do not blindly apply "subtract two" to every prefix: /31 point-to-point links and /32 host routes have different interpretations. The addresses in 192.0.2.0/24 are documentation examples here, not a suggested production allocation.

Worked example · Work out 192.0.2.64/26

  1. Thirty-two minus twenty-six leaves six variable bits, so the block contains 2⁶ = 64 addresses.
  2. The range begins at .64 and ends at .127. Conventional host addresses are .65 through .126.
  3. The address .100 is inside this range, while .130 is in the next block. The boundary is determined by prefix bits, not by the last digit looking similar.

Result: Range arithmetic makes route and subnet discussions checkable.

Go deeper: [5] RFC 4632: Classless Inter-domain Routing · [6] RFC 3021: 31-bit prefixes on point-to-point links

Use a parser and learn IPv6 separately

Check a documentation subnet python
from ipaddress import ip_network, ip_address
network = ip_network("192.0.2.64/26")
print(network.num_addresses)
print(network.broadcast_address)
print(ip_address("192.0.2.100") in network)
Expected result
64
192.0.2.127
True

IPv6 uses 128-bit addresses written in hexadecimal groups. A run of zero groups can be compressed once with a double colon, and leading zeros in groups may be omitted. The documentation prefix 2001:db8::/32 is useful in examples. IPv6 does not use IPv4-style broadcast. Link-local addresses have local-link scope, so the interface can be necessary to interpret an address correctly. Do not treat every address string as a globally reachable endpoint.

PurposeIPv4 exampleIPv6 example
Loopback on this machine127.0.0.1::1
Documentation192.0.2.102001:db8::10
Address length32 bits128 bits

Private addressing and translation often appear together, but they are distinct ideas. An address can be locally meaningful without being globally routable. NAT changes addressing information as traffic crosses a boundary and maintains state for many common arrangements. It is not equivalent to an application authorization policy. When a service binds only to 127.0.0.1, it is intended for local access; binding to every interface can expose it to a much larger audience.

Go deeper: [27] Python 3.11 ipaddress reference · [7] RFC 4291: IPv6 addressing architecture · [8] RFC 3849: IPv6 documentation prefix

Keep these ideas

  • A prefix is a range of bits, not a visual naming convention.
  • Loopback, local scope, routing, and permission are different concepts.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

4.1 · Practice task

Find the address count, network address, and conventional broadcast address for 198.51.100.128/27.

Hint: A /27 has five variable bits.

Read the worked solution

4.2 · Practice task

Why should a local practice server bind to 127.0.0.1 rather than 0.0.0.0 by default?

Hint: The binding determines which local destination addresses can accept connections.

Read the worked solution

Chapter 05

Follow routes, hop limits, and packet size

Learn why a reachable destination can still fail for larger traffic.

By the end of this chapter
  • Apply longest-prefix matching
  • Explain MTU, fragmentation boundaries, and ICMP evidence

Forward one hop with a routing table

A router does not need a complete turn-by-turn itinerary for each packet. It consults forwarding information and selects an outgoing interface and next hop. When multiple prefixes match a destination, the most specific applicable prefix normally wins: this is longest-prefix matching. A default route is the least-specific fallback. Routing protocols and administrative configuration determine how forwarding information is learned; the lookup is the per-packet action using that information.

Consider routes for 0.0.0.0/0, 10.0.0.0/8, and 10.20.0.0/16. A destination 10.20.4.9 matches all three, but /16 is more specific than /8 or /0. This does not mean the longest printed address wins. It is the number of matching prefix bits. A missing return route can break a conversation even when the forward packet reaches its destination. Packet journeys must work in both directions for request-response applications.

Choose the most specific matching route python
from ipaddress import ip_network, ip_address
routes = [ip_network(x) for x in
          ["0.0.0.0/0", "10.0.0.0/8", "10.20.0.0/16"]]
destination = ip_address("10.20.4.9")
match = max((r for r in routes if destination in r),
            key=lambda r: r.prefixlen)
print(match)
Expected result
10.20.0.0/16

Go deeper: [3] RFC 1812: IPv4 router requirements · [27] Python 3.11 ipaddress reference

Bound loops and respect the path’s packet size

IPv4 TTL and IPv6 Hop Limit limit how long a packet can circulate through forwarding loops by decreasing at routers. They are not estimates of remaining wall-clock seconds in ordinary forwarding. When the value runs out, a router may send an ICMP error. Traceroute-style tools exploit this behavior, but missing replies can also mean filtering or rate limiting. A star in a trace is an absence of a particular response, not a proof that the router stopped forwarding all traffic.

The maximum transmission unit, MTU, bounds the packet size that a link can carry without link-specific fragmentation. A path can include links with smaller limits than the sender expects. IPv6 routers do not fragment packets in transit; the source must adapt using the relevant mechanisms. In IPv4, fragmentation depends on packet flags and circumstances. Blocking all ICMP can interfere with useful error reporting, including packet-size discovery. A TCP connection that opens but stalls on larger transfers deserves investigation beyond DNS.

Large-packet trouble after a successful connectionA small handshake fits, a larger packet exceeds a later link limit, and useful error feedback allows the sender to reduce its packet size.Small exchangeConnection appears healthyLarge packetA smaller-MTU link cannot carry itSize feedbackNetwork can report the constraintSender adaptsSend suitably sized packets
Large-packet trouble after a successful connection. A small handshake fits, a larger packet exceeds a later link limit, and useful error feedback allows the sender to reduce its packet size.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [9] RFC 8200: IPv6 specification · [10] RFC 1191: IPv4 Path MTU Discovery · [11] RFC 4443: ICMPv6

Keep these ideas

  • Route matching needs both membership and prefix length.
  • Successful small packets do not prove large transfers work.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

5.1 · Practice task

Which route wins for 10.20.4.9 if /0, 10.0.0.0/8, and 10.20.0.0/16 are present? Would /24 for 10.20.4.0 change the answer?

Hint: Compare prefix lengths among routes that actually contain the destination.

Read the worked solution

5.2 · Practice task

A site resolves and a TCP handshake succeeds, but a larger response repeatedly stalls. Name two hypotheses and a discriminating test.

Hint: Test one variable, including packet-size assumptions.

Read the worked solution

Chapter 06

Resolve names and understand caching

Trace where an address answer comes from and why different learners can see different answers.

By the end of this chapter
  • Distinguish a recursive resolver from an authoritative server
  • Explain TTL, record types, and cached negative answers

A name is a lookup key, not a machine

DNS maps names to typed resource records. An A record supplies IPv4 address data, an AAAA record supplies IPv6 address data, and a CNAME points to another name. The same name can have multiple records, and different services need different record types. A URL includes more than a DNS name: the scheme, port, path, and query are interpreted elsewhere. DNS does not know whether a requested course page exists inside a web application.

A typical application asks a local resolver interface, which may use caches and then a recursive DNS service. On a cache miss, the recursive resolver follows delegations toward the authoritative servers for the relevant zone. Root and top-level-domain servers direct the search; they do not usually store every host’s final address. The authoritative server serves the zone’s data, while the recursive resolver does work on a client’s behalf. Keeping these roles separate explains why changing one local setting may affect only some users.

A simplified uncached lookupThe client asks a recursive resolver. That resolver follows delegations and returns the final answer; real caches can remove many of these exchanges.ClientRecursive resolverAuthoritativeservice1. Ask for the A/AAAA records2. Follow delegations, then ask the zone3. Return records and TTLs4. Return an answer; keep permitted cache entries
A simplified uncached lookup. The client asks a recursive resolver. That resolver follows delegations and returns the final answer; real caches can remove many of these exchanges.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [12] RFC 1034: DNS concepts and facilities · [13] RFC 1035: DNS implementation and specification

Caches make time part of the answer

A TTL describes how long a cached record may be reused according to DNS rules. It is not a promise that every client will forget an old address at the same wall-clock instant. A resolver may have cached the previous value shortly before a change. Applications and operating systems can have additional caching behavior. Negative answers can also be cached. This is why a recent deployment should be checked from the authoritative source and from the resolver actually used by the failing client.

Ask the operating system about local address candidates python
import socket
answers = socket.getaddrinfo("localhost", 8000,
                             type=socket.SOCK_STREAM)
families = sorted({"IPv6" if a[0] == socket.AF_INET6 else "IPv4"
                   for a in answers})
print(families)
Expected result
Typical: ['IPv4', 'IPv6']; available families vary by host configuration.

The local example avoids relying on an external DNS service, but localhost may be supplied by local configuration rather than a network DNS query. That distinction is part of the lesson: an API result does not prove which cache or source supplied it. When diagnosing a real name, record the name, record type, resolver, returned values, TTL information, and time. Do not paste credentials from a URL query into a public troubleshooting report.

Go deeper: [26] Python 3.11 socket reference · [14] RFC 2308: DNS negative caching

Keep these ideas

  • DNS answers have type, source, and time.
  • Resolution, encrypted transport, and application health are separate checks.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

6.1 · Practice task

The authoritative A record changed five minutes ago, but one user still reaches an old address. Explain a plausible cause and useful evidence.

Hint: Look at when that user’s recursive resolver cached its answer.

Read the worked solution

6.2 · Practice task

Why does a successful DNS lookup not prove the HTTPS service is healthy?

Hint: List the remaining stages after address selection.

Read the worked solution

Chapter 07

Choose UDP and define application messages

Keep datagrams, delivery guarantees, and your own protocol contract distinct.

By the end of this chapter
  • Explain what UDP does and does not supply
  • Design bounded message handling and detect truncation risks

UDP supplies datagrams, not reliable delivery

UDP exposes message-oriented datagrams between endpoints identified using IP addresses and ports. A receiving application reads one datagram at a time rather than a continuous byte stream. UDP itself does not retransmit a lost message, reorder application messages, or guarantee that any receiver exists. Those omissions can be useful when an application wants fresh data instead of delayed old data, but they move responsibility into the design of the application protocol.

A port number helps an operating system select a local communication endpoint. It is not a process identifier or a permanent personal identity. A server often uses a known port while a client receives a temporary local port. Different transport protocols have distinct port spaces. The combination of addresses, ports, and protocol helps distinguish conversations; NAT and other middleboxes may rewrite some values along the path.

A bounded UDP echo on loopback python
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
    server.bind(("127.0.0.1", 0))
    server.settimeout(1.0)
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
        client.settimeout(1.0)
        client.sendto(b"lesson?", server.getsockname())
        data, peer = server.recvfrom(1024)
        server.sendto(data.upper(), peer)
        reply, _ = client.recvfrom(1024)
        print(reply.decode("ascii"))
Expected result
LESSON?

Go deeper: [15] RFC 768: UDP · [26] Python 3.11 socket reference

Freshness, retries, and congestion still need design

Suppose a classroom activity sends a cursor position ten times per second. If one update is lost, a newer update can make the old one irrelevant. Compare that with recording an assessment submission: losing the only message silently is unacceptable. The choice depends on the required application result. Adding a retry timer does not automatically make a UDP design correct. A late original and a retry can both arrive, so request identity, duplicate handling, and bounded retries may be necessary.

Large datagrams can require fragmentation and may be dropped more often when one fragment is lost. Receive buffers also impose bounds: an application that supplies a buffer too small for a datagram risks losing the remainder rather than reading it on the next call as if it were TCP. Platform APIs provide different ways to observe truncation. Define maximum message size deliberately and reject invalid lengths. An unbounded parser gives a remote sender control over memory consumption.

A datagram application must define missing behaviorUDP carries a datagram, while the application separately decides whether to discard stale updates, retry important work, and detect duplicates.Application decisionIs freshness or eventual completion required?Datagram sendAn individual message enters the networkPossible outcomesArrival, loss, duplication, reordering, or delayApplication responseApply sequence checks, bounded retry, or discard policy
A datagram application must define missing behavior. UDP carries a datagram, while the application separately decides whether to discard stale updates, retry important work, and detect duplicates.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [16] RFC 8085: UDP usage guidelines · [26] Python 3.11 socket reference

Keep these ideas

  • Datagrams preserve messages; applications define useful outcomes.
  • Bound size, rate, retries, and duplicate handling.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

7.1 · Practice task

You retry an assessment submission after a UDP timeout. Why might the server record two submissions?

Hint: A missing reply does not prove a missing request.

Read the worked solution

7.2 · Practice task

For live pointer positions, should an old delayed update always be applied after a new one?

Hint: Decide what makes an update useful.

Read the worked solution

Chapter 08

Understand TCP as a reliable byte stream

Use sequence numbers and windows without mistaking a connection for a completed operation.

By the end of this chapter
  • Explain stream framing, acknowledgments, and retransmission
  • Separate flow control from congestion control

A connection orders bytes, not your objects

TCP presents an ordered byte stream to applications. It detects missing stream data and retransmits according to its mechanisms, hiding many network irregularities from the reader. It does not preserve the boundaries of send calls. Two writes may arrive in one read; one write may require several reads. A correct application protocol therefore needs a way to find messages: a fixed length, a length prefix, a delimiter with clear escaping, or another defined format.

A common TCP connection setup exchanges SYN, SYN-ACK, and ACK, establishing state and initial sequence information. After setup, sequence numbers identify positions in the byte stream and acknowledgments communicate received progress. An acknowledgment from the remote TCP stack does not prove that the remote application committed data to a database or even finished interpreting it. Application success needs an application-level response with defined meaning.

Setup and application meaning are separateA simplified TCP handshake precedes the request and response. The final application response is the evidence about application work, not the handshake itself.ClientServer1. SYN: establish sequence state2. SYN-ACK3. ACK, then application request bytes4. Application response after its defined work
Setup and application meaning are separate. A simplified TCP handshake precedes the request and response. The final application response is the evidence about application work, not the handshake itself.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [17] RFC 9293: TCP

Two windows protect different resources

Flow control protects a receiver from more data than it can currently accept. Congestion control adjusts sending to conditions in the network. A receiver can have plenty of memory while the path is congested; a path can be quiet while the application is not draining its receive buffer. The sender must respect both kinds of constraints. A large configured buffer cannot magically repair packet loss, an overloaded service, or a slow reader.

A parser must accumulate a complete framed message python
buffer = b""
chunks = [b"HEL", b"LO\nNE", b"XT\n"]
messages = []
for chunk in chunks:
    buffer += chunk
    while b"\n" in buffer:
        message, buffer = buffer.split(b"\n", 1)
        messages.append(message.decode("ascii"))
print(messages)
print(buffer)
Expected result
['HELLO', 'NEXT']
b''

This parser demonstrates stream boundaries without opening a connection. It is incomplete as a network service until it also limits buffer size, decides what EOF means, and defines encoding and error handling. A malicious or mistaken peer could otherwise send bytes forever without a newline. A zero-length recv result indicates the peer has orderly closed its sending side; it is not an empty application message. Treat partial data at EOF according to your framing rules.

MechanismProtects or suppliesDoes not establish
TCP orderingByte-stream orderJSON/message boundaries
Receive windowReceiver capacityNetwork capacity
Congestion controlPath sharing and overload responseBusiness-level completion

Go deeper: [17] RFC 9293: TCP · [18] RFC 5681: TCP congestion control · [26] Python 3.11 socket reference

Keep these ideas

  • A stream needs an application framing rule.
  • Network acknowledgment is not business confirmation.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

8.1 · Practice task

A client calls sendall twice and the server calls recv once. How many application messages will recv return?

Hint: A TCP read returns available stream bytes up to a limit.

Read the worked solution

8.2 · Practice task

A payment request was sent, then the connection failed before the client saw a response. Did the payment happen?

Hint: Transport failure can leave the application result unknown.

Read the worked solution

Chapter 09

Use TLS for confidentiality and server identity

Know what HTTPS protects and which decisions still belong to the application.

By the end of this chapter
  • Explain certificate and hostname validation
  • Distinguish encryption, authentication, and authorization

Encryption needs an authenticated peer

Without protection, an observer on a relevant part of a network path may be able to read or modify application traffic. TLS establishes protected communication using negotiated cryptographic parameters and keys. In common HTTPS use, the client also validates the server’s certificate chain and the hostname it intended to reach. Encrypting a conversation with the wrong peer does not solve impersonation, so validation is part of the security property rather than an optional inconvenience.

A certificate connects an identity claim and a public key under a trust model. The browser or client checks relevant conditions such as names, trust chain, and validity. The exact validation policy and revocation behavior depend on the client and environment. Do not solve a certificate error by permanently disabling checks. An unexpected certificate can indicate a hostname error, missing local trust configuration, interception, or an actual attack; investigate the specific evidence.

Trust before sensitive application dataThe client checks the intended name and certificate while keys are established, then uses the protected connection for application messages.Intended nameThe user or application chooses a hostnameHandshake and identityNegotiate keys and validate the server identityProtected recordsDetect tampering and conceal content on the TLS linkApplication policyCheck the signed-in user and allowed operation
Trust before sensitive application data. The client checks the intended name and certificate while keys are established, then uses the protected connection for application messages.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [19] RFC 8446: TLS 1.3 · [28] Python 3.11 ssl reference

A secure channel has a defined boundary

TLS does not make the application’s content truthful, remove server vulnerabilities, or grant a user permission to access a course account. Authentication asks who is participating under some identity system. Authorization asks which operation that identity may perform on which resource. If a reverse proxy terminates TLS, traffic behind that proxy needs its own appropriate protection and trust design. Describe the endpoints of each protected connection instead of drawing one padlock over an entire distributed system.

Create a validating client context python
import ssl
context = ssl.create_default_context()
print(context.check_hostname)
print(context.verify_mode == ssl.CERT_REQUIRED)
Expected result
True
True

The example constructs a normal validating context without connecting to a remote host. A full client must wrap a connected socket with the intended server_hostname and handle errors. SNI commonly carries a hostname indication so a shared server can choose configuration; it is not the same thing as certificate validation. Some metadata can remain visible outside encrypted application content. This guide does not teach you to build cryptographic primitives; use maintained libraries and their documented defaults.

Go deeper: [28] Python 3.11 ssl reference · [20] RFC 9110: HTTP semantics

Keep these ideas

  • Protect the channel and validate the intended peer.
  • Authorization remains an application responsibility.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

9.1 · Practice task

An API is reachable only over HTTPS, but changing /users/12 to /users/13 reveals another learner’s data. Which control failed?

Hint: The channel can be secure while the requested operation is forbidden.

Read the worked solution

9.2 · Practice task

A certificate is valid for api.example.test but the client requests courses.example.test. Why should a normal client reject a mismatch?

Hint: The name chosen by the client is part of the identity being checked.

Read the worked solution

Chapter 10

Read HTTP requests, responses, caches, and versions

Connect browser behavior to explicit application-layer semantics.

By the end of this chapter
  • Interpret methods, status codes, headers, and bodies
  • Compare HTTP semantics with transport-version changes

A request is a deliberate operation

HTTP defines request and response semantics: a method, a target, fields, and optional content. GET requests a representation. POST asks a resource to process supplied content under its defined behavior. PUT generally creates or replaces the state of a target resource according to the service contract. Method names carry shared semantics that clients, caches, and intermediaries can use. Choosing POST for every action loses useful meaning, while calling an operation GET does not make a harmful implementation safe.

Status codes are grouped signals, not complete diagnoses. A 2xx response indicates a successful class of result under the method; 3xx concerns redirection; 4xx indicates a client-side request or policy condition; 5xx indicates a server-side failure to fulfill the request. Read the specific code and relevant fields. A 401 response concerns authentication requirements; 403 commonly indicates refusal under policy. Returning a success status with an error buried in text makes automated handling harder.

A small HTTP/1.1 exchange text
GET /lessons/python HTTP/1.1
Host: localhost:8000
Accept: application/json


HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 17

{"title":"Loops"}
Expected result
The JSON body is 17 ASCII bytes. CRLF separates HTTP/1.1 header lines.

The written exchange is a reading aid, not a production HTTP parser. Framing, duplicate fields, intermediaries, and malformed inputs have security consequences. Use a maintained HTTP implementation rather than improvising a parser from this example. Header names and representation bytes are different layers of interpretation; a declared media type tells the recipient how the application intends the content to be read.

Go deeper: [20] RFC 9110: HTTP semantics · [22] RFC 9112: HTTP/1.1

Reuse changes performance and freshness

A cache can reuse an allowed stored response instead of contacting the origin for every request. Freshness rules decide when reuse is permitted without validation; validators such as ETags can support conditional requests. Cache identity and variation matter: content for one signed-in user must not accidentally become another user’s public response. "Cache it" is incomplete advice until you state the key, lifetime, invalidation behavior, privacy rules, and the cost of stale data.

HTTP/2 multiplexes streams over a connection with binary framing, while HTTP/3 maps HTTP semantics onto QUIC. These versions change transport behavior without redefining GET as a different business operation. Multiplexing reduces some application-level head-of-line blocking patterns, but shared resources and congestion still exist. QUIC’s streams do not guarantee zero latency or prevent all loss-related delay. Measure a real workload rather than treating a protocol version label as a performance promise.

A cache decision needs a policyA request maps to a cache key, freshness decides whether reuse is allowed, and stale entries can require validation with the origin.Request identityMethod, target, and relevant variationStored responseWas this representation allowed to be stored?Freshness checkCan it be reused now under its policy?Reuse or validateReturn allowed content or contact the origin
A cache decision needs a policy. A request maps to a cache key, freshness decides whether reuse is allowed, and stale entries can require validation with the origin.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [21] RFC 9111: HTTP caching · [23] RFC 9113: HTTP/2 · [24] RFC 9114: HTTP/3 · [25] RFC 9000: QUIC

Keep these ideas

  • HTTP methods and statuses communicate a reusable contract.
  • Every cache requires correctness and privacy rules.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

10.1 · Practice task

A GET response depends on the signed-in learner. Why is a cache keyed only by URL risky?

Hint: Two users can request the same URL but be entitled to different content.

Read the worked solution

10.2 · Practice task

Does moving from HTTP/1.1 to HTTP/3 automatically make an expensive database query fast?

Hint: Separate transport waiting from application computation.

Read the worked solution

Chapter 11

Build a bounded TCP protocol on localhost

Turn stream rules into runnable application behavior.

By the end of this chapter
  • Implement bounded line framing
  • Handle timeouts, EOF, and resource cleanup

Define the contract before writing the loop

Our small protocol accepts one ASCII request line ending with a newline. The maximum line length is 64 bytes including the delimiter. The valid request is PING, and the successful response is PONG followed by a newline. These choices are intentionally small so that every boundary can be tested. A real application would normally use an existing protocol, but building one bounded toy protocol reveals responsibilities that higher-level libraries handle for you.

A server first binds an address, listens for connections, and accepts one. The accepted socket represents a connection; the listening socket remains responsible for new arrivals. Using context managers closes both resources even when an exception occurs. Timeouts limit how long a blocking operation can wait in this exercise, but a per-call timeout is not a complete end-to-end deadline: a peer that continually sends a trickle can keep making partial progress. Stronger production bounds include an overall monotonic deadline.

Read one bounded line from a connected socket python
def read_line(sock, limit=64):
    data = bytearray()
    while len(data) < limit:
        part = sock.recv(1)
        if not part:
            raise EOFError("connection closed before newline")
        data.extend(part)
        if part == b"\n":
            return bytes(data[:-1])
    raise ValueError("line exceeds limit")
Expected result
read_line returns the bytes before newline, or raises an explicit framing error.

Reading one byte at a time is easy to reason about but inefficient for large traffic. Production parsers usually read chunks into a bounded buffer and preserve bytes after a delimiter for the next message. Do not optimize away correctness: first define what happens for an exact-limit line, multiple messages in one read, invalid encoding, and EOF halfway through a request. Every accepted length should have one unambiguous meaning.

Go deeper: [26] Python 3.11 socket reference

Use an isolated local exchange

Run one complete client/server exchange python
import socket
from threading import Thread

def serve(listener):
    with listener:
        conn, _ = listener.accept()
        with conn:
            conn.settimeout(1)
            request = read_line(conn)
            conn.sendall(b"PONG\n" if request == b"PING"
                         else b"ERROR\n")

listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(1)
listener.settimeout(2)
address = listener.getsockname()
worker = Thread(target=serve, args=(listener,))
worker.start()
with socket.create_connection(address, timeout=1) as client:
    client.sendall(b"PING\n")
    print(read_line(client).decode("ascii"))
worker.join(timeout=3)
assert not worker.is_alive()
Expected result
PONG; define read_line from the preceding example in the same file.

Port zero asks the operating system to choose an available local port, which avoids hard-coding a port that another program may already use. The client reads the actual bound address and connects only after listen is called. The thread is present to let both sides of the exchange run in one process for the lab. It is not a scalability recommendation. A server accepting untrusted clients needs further concurrency limits, deadlines, error responses, logging, and application authorization.

Go deeper: [26] Python 3.11 socket reference

Keep these ideas

  • A protocol needs limits and an EOF policy.
  • Close resources and distinguish a toy lab from a deployed service.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

11.1 · Practice task

What happens when a client sends PING without a newline and closes? Explain the intended error.

Hint: An orderly transport close is different from a complete application frame.

Read the worked solution

11.2 · Practice task

Improve the reader’s tests before making it faster. Which boundaries should be covered?

Hint: Test the maximum size, missing delimiter, extra bytes, and split reads.

Read the worked solution

Chapter 12

Design network trust and observability deliberately

Keep identities, permissions, boundaries, and evidence visible.

By the end of this chapter
  • Separate network access from application permission
  • Choose useful logs and timeout/retry policies

A reachable service is not automatically an authorized service

A firewall can restrict which traffic is allowed through a boundary based on configured rules. It cannot by itself decide every business permission inside an allowed application session. An organization may allow HTTPS to a service, while the service must still reject one learner reading another learner’s records. Similarly, a private address does not prove that the caller is trustworthy. Shared networks, compromised hosts, and misconfigured routes make implicit trust fragile.

Use layers of controls with named responsibilities: bind the service to the intended interfaces, restrict network access where appropriate, authenticate the caller, authorize each operation, validate input, bound resource use, and record useful outcomes. These controls support each other. The goal is not to stack decorative security products; it is to make each unwanted outcome harder and to know which control would detect or prevent it.

Trust checks at different boundariesNetwork reachability permits a connection, authentication establishes a caller identity, authorization permits a resource operation, and validation bounds what the operation may consume.ReachabilityCan this source connect to the intended port?AuthenticationWhich caller identity is established?AuthorizationMay that identity act on this resource?Validation and limitsIs the input valid and is work bounded?
Trust checks at different boundaries. Network reachability permits a connection, authentication establishes a caller identity, authorization permits a resource operation, and validation bounds what the operation may consume.Scroll horizontally to read the full diagram on a small screen.
A small retry budget calculation python
attempt_seconds = 0.8
backoffs = [0.1, 0.2]
attempts = 3
worst_case = attempts * attempt_seconds + sum(backoffs)
print(round(worst_case, 1))
Expected result
2.7

Go deeper: [19] RFC 8446: TLS 1.3 · [20] RFC 9110: HTTP semantics

Evidence should explain stages without leaking secrets

Record a request identifier, the operation, stage timings, outcome class, and bounded diagnostic context. Separate name resolution, connection establishment, TLS, server response wait, and body transfer where your client exposes them. A single "request failed" line hides too many causes. Do not place session cookies, passwords, authorization tokens, or full sensitive payloads into logs. An observability feature that creates a new secret archive can make a failure more expensive.

Timeouts and retries are a resource budget. If three attempts each consume up to 0.8 seconds and backoffs total 0.3 seconds, the modeled budget is 2.7 seconds before other overhead. Check this against the caller’s deadline. Randomized backoff can reduce synchronized retry waves, but retries should be bounded and appropriate for the operation. If a timed-out request may already have changed state, use an application contract that supports reconciliation or safe duplicate handling.

ObservationUseful next questionUnsupported leap
Connection refusedIs a listener running at that address/port?The password is wrong
TLS name mismatchIs the endpoint/certificate name correct?Disable validation forever
HTTP 403Which application policy refused access?The network is down

Troubleshooting should preserve evidence before changing several controls at once. Record the failing endpoint, client environment, exact time, and reproducible steps. Change one variable, predict the observation, and compare. If the result contradicts the hypothesis, update the hypothesis instead of inventing a story that protects it. Good network engineering is disciplined uncertainty management, especially when multiple teams own different stages.

Go deeper: [31] curl official manual · [20] RFC 9110: HTTP semantics

Keep these ideas

  • Name the security boundary and the protected outcome.
  • Measure failure stages and keep retries inside a total budget.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

12.1 · Practice task

Why is a successful TCP connection an insufficient authorization check for a progress-update API?

Hint: The transport endpoint does not encode ownership of a learner record.

Read the worked solution

12.2 · Practice task

Your caller has a two-second deadline. Is the demonstrated 2.7-second retry budget acceptable?

Hint: Budget includes all attempts, waits, and overhead.

Read the worked solution

Chapter 13

Diagnose by narrowing the failing stage

Use repeatable local experiments instead of random configuration changes.

By the end of this chapter
  • Build an evidence-first troubleshooting checklist
  • Read curl timing and distinguish local from remote failures

Start with a small known service

Create a temporary directory containing one harmless text file, then run Python’s built-in HTTP server bound to loopback. This gives you a known endpoint whose behavior you control. Run the server in its own terminal so you can see request logs and stop it with Control-C. Do not serve a directory containing secrets or source environment files. The exercise is about observing HTTP and process boundaries, not exposing your computer to other machines.

Local HTTP lab, terminal one shell
mkdir -p /tmp/openlearning-network-lab
cd /tmp/openlearning-network-lab
printf "hello learner\n" > lesson.txt
python3 -m http.server 8000 --bind 127.0.0.1
Expected result
A server starts on port 8000. If that port is busy, choose another and use it consistently.
Local HTTP lab, terminal two shell
curl --connect-timeout 1 --max-time 3 -i \
  http://127.0.0.1:8000/lesson.txt
Expected result
Representative: HTTP/1.0 200 OK, response headers, then hello learner.

Request a missing file and compare the 404 response with the connection error after you stop the server. In the first case an HTTP service deliberately reports a missing target. In the second case no HTTP response may exist because the transport connection was not established. These are different failure classes, so they should not share one vague UI message or one remediation checklist.

Go deeper: [29] Python 3.11 http.server reference · [31] curl official manual

Ask a question that the next measurement can answer

Use a sequence: confirm the endpoint string, resolve its name if needed, check the selected address and port, establish the transport, validate TLS when used, inspect the HTTP result, and finally inspect application data and dependencies. Not every tool observes every stage. Browser developer tools can show request timing and response metadata; curl can expose similar stages from a terminal. Local-hostname and direct-loopback tests can deliberately remove external DNS from an experiment.

Capture selected timing stages shell
curl --silent --show-error --output /dev/null \
  --connect-timeout 1 --max-time 3 \
  --write-out "connect=%{time_connect} first_byte=%{time_starttransfer} total=%{time_total}\n" \
  http://127.0.0.1:8000/lesson.txt
Expected result
Times vary. For this plain HTTP loopback test, TLS time is not part of the exchange.

Timing variables are cumulative measurements from the start of an operation, not independent durations that should all be added together. A large first-byte wait after a fast connection suggests a different investigation from a slow connect. Repeat a controlled number of times and examine variability. One unusually fast cached request and one cold request are not a fair comparison. Keep a short experiment log so that someone else can reproduce the conclusion.

Worked example · A useful incident note

  1. State the exact failing URL without secret query data, the client, and the observation time.
  2. Record whether the name resolved, whether transport/TLS succeeded, and the status or error class.
  3. Compare with the known loopback service and change only one relevant variable.
  4. Write the result and the next remaining uncertainty rather than declaring the entire network good or bad.

Result: A small honest report is more actionable than a screenshot plus the word "broken".

Go deeper: [31] curl official manual · [32] MIT Computer System Engineering, Spring 2018

Keep these ideas

  • Compare failures at the same stage.
  • Keep timing definitions and experimental conditions explicit.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

13.1 · Practice task

Your local lab returns 404 for /missing.txt. Should you reset your router? Explain the next useful check.

Hint: You already received an application-layer response.

Read the worked solution

13.2 · Practice task

The connection stage is consistently quick, but first-byte time grows with concurrent requests. What should you investigate?

Hint: Waiting can move into the service or its dependencies.

Read the worked solution

Chapter 14

Capstone: make a local learning client predictable

Combine framing, deadlines, failure classification, and an experiment report.

By the end of this chapter
  • Build a tested local request-response protocol
  • Explain each guarantee and each deliberate limitation

Specify behavior as testable cases

Your capstone is a local service that receives a bounded line such as TOPIC python and returns one short response. Begin with a written contract: ASCII request encoding, newline delimiter, a maximum of 64 bytes including the delimiter, a two-second operation deadline, and a fixed set of allowed topic names. An unknown topic produces an explicit NOT_FOUND response. Invalid encoding or an overlong request is a protocol error. The server handles one connection at a time in the first version.

These limits are not arbitrary decoration. They let you predict memory use, decide when a request is complete, and distinguish an unknown course from a broken connection. Keep the course lookup as a pure function so it can be tested without networking. Keep parsing separate from transport. The client should report connect failure, timeout, incomplete frame, invalid response, and valid NOT_FOUND as different outcomes. Clear distinctions help a learner understand what action is useful next.

Start with the pure application behavior python
TOPICS = {"python": "functions and collections",
          "networks": "packets and protocols"}

def reply_for(line):
    parts = line.split(" ")
    if len(parts) != 2 or parts[0] != "TOPIC":
        return "BAD_REQUEST"
    topic = parts[1]
    return "OK " + TOPICS[topic] if topic in TOPICS else "NOT_FOUND"

assert reply_for("TOPIC python") == "OK functions and collections"
assert reply_for("TOPIC unknown") == "NOT_FOUND"
assert reply_for("python") == "BAD_REQUEST"
print("application cases passed")
Expected result
application cases passed

Wire reply_for into the bounded reader and local server from the socket chapter. Decode only a complete request and encode the response before sendall. Give the listening socket and accepted connection bounded waits. For a true total deadline, calculate remaining time from a monotonic clock before each blocking call, rather than granting a fresh full timeout after every received byte. Document which guarantee your implementation actually enforces.

Go deeper: [26] Python 3.11 socket reference · [30] Python 3.11 time reference

Test the failure story, then write the report

Keep responsibilities independently testableA client transport obtains bytes, a framing parser finds one bounded request, the pure handler chooses a reply, and response framing carries it back.Client transportConnect, bound waiting, and classify failureRequest framingFind newline within the size limitPure handlerMap a valid command to an application resultResponse framingEncode one bounded, documented reply
Keep responsibilities independently testable. A client transport obtains bytes, a framing parser finds one bounded request, the pure handler chooses a reply, and response framing carries it back.Scroll horizontally to read the full diagram on a small screen.

Test an ordinary topic, an unknown topic, a malformed command, an empty line, an exact-boundary line, a missing newline, and a peer that closes halfway through. Test the parser using different chunk boundaries so it does not depend on local scheduling. For integration, use a dynamically chosen loopback port and ensure worker threads exit even on failure. Do not leave background listeners running after the lab. A cleanup step is part of a reproducible experiment.

Your final report should include the protocol contract, a diagram, successful output, at least three deliberately triggered failures, and a table of expected versus observed behavior. Explain why this exercise lacks remote authentication, TLS termination, high-concurrency control, and durable storage. Those are planned extensions, not properties inherited from opening a socket. Compare the design with using an established HTTP server library and explain when the custom protocol would be the wrong engineering choice.

Go deeper: [26] Python 3.11 socket reference · [32] MIT Computer System Engineering, Spring 2018

Keep these ideas

  • Correctness includes the negative cases and cleanup.
  • A guarantee belongs in the contract only after it is implemented and tested.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

14.1 · Practice task

Add a total deadline to repeated reads. Why is resetting a two-second timeout for every byte insufficient?

Hint: Imagine a peer sending one byte every second forever.

Read the worked solution

14.2 · Practice task

Write acceptance criteria that distinguish a finished teaching lab from a production service.

Hint: List observable behaviors and explicitly excluded guarantees.

Read the worked solution

Practice with feedback

Worked solutions

These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.

Chapter 1 · Follow one message through the network

Solution 1.1

The browser reached an HTTP-speaking endpoint and received a parseable response. If this was HTTPS with normal validation, the TLS exchange also succeeded with the authenticated endpoint. The requested resource was not found there. The response does not prove that the intended application route, deployment version, or backend data is correct; a proxy can generate the response.

Return to the task

Solution 1.2

There are ten characters, but é occupies two UTF-8 bytes, making eleven bytes. A sender that declares a length of ten and then writes eleven bytes leaves a byte behind for the next message. A receiver that decodes arbitrary packet fragments can also split a multibyte character. Frame bytes first, then decode a complete payload.

Return to the task

Chapter 2 · Calculate delay, throughput, and queues

Solution 2.1

The message is 16,000 bits. Dividing by 2,000,000 gives 0.008 seconds, or 8 ms. This excludes propagation and any response. If the application waits for a reply, add the relevant forward and reverse delays and server processing rather than calling 8 ms the full request latency.

Return to the task

Solution 2.2

A long tail may come from queueing, pauses, slow dependencies, retransmissions, or expensive requests. More link capacity helps only if transmission or network queueing is the limiting cause. Measure time in stages and correlate tails with load before changing capacity. Averages alone hide the users experiencing the 800-ms responses.

Return to the task

Chapter 3 · Understand local delivery: Ethernet, Wi-Fi, switches, and ARP

Chapter 4 · Read IPv4, IPv6, and CIDR without guessing

Solution 4.1

The block contains 32 addresses. It starts at 198.51.100.128 and ends at 198.51.100.159, which is the broadcast address for a conventional broadcast-capable subnet. Ordinary hosts are .129–.158. The next /27 starts at .160. Explain the special context before applying host-count rules to /31 or /32.

Return to the task

Solution 4.2

Loopback keeps this exercise reachable from the same machine rather than every configured network interface. Binding to 0.0.0.0 accepts IPv4 connections directed at any local interface, subject to firewall rules. This is useful when deliberately sharing a service, but it is an unnecessary exposure for a personal lab.

Return to the task

Chapter 5 · Follow routes, hop limits, and packet size

Solution 5.1

The /16 wins initially. If 10.20.4.0/24 is available and applicable, it becomes the most specific match and wins. An unrelated /28 would not win simply because 28 is larger; the destination must fall inside the prefix first.

Return to the task

Solution 5.2

One hypothesis is an MTU/size-discovery problem; another is server delay or loss under load. Compare small and larger responses on an owned endpoint and inspect endpoint timing and permitted packet/error observations. Repeating DNS queries would not distinguish these well because resolution already succeeded. Do not disable all firewall protections to test a vague suspicion.

Return to the task

Chapter 6 · Resolve names and understand caching

Solution 6.1

The user’s resolver may have a still-valid old cached record, or the application may cache its own address choice. Compare the authoritative response and the affected resolver’s response for the same record type, with timestamps and TTLs. Also check AAAA records because an IPv6-capable client may choose a different address family. A changed A record alone does not describe every connection path.

Return to the task

Solution 6.2

The client must still reach an address and port, establish the transport and TLS connection, validate server identity, send a request, and receive a useful application response. DNS can succeed for a stopped service or a misconfigured certificate. Test each stage rather than replacing the DNS configuration after every failed page load.

Return to the task

Chapter 7 · Choose UDP and define application messages

Solution 7.1

The first submission may have reached the server and its acknowledgment may have been lost. The retry can then reach the server as a second request. Include an application request identifier and specify duplicate handling, or use a suitable existing reliable protocol with application-level idempotency. Transport reliability alone still cannot decide business semantics.

Return to the task

Solution 7.2

Usually no: attach an ordering or generation value and ignore stale positions so the pointer does not jump backward in time. This is a freshness policy, not a UDP guarantee. Wraparound, clock assumptions, reconnection, and the identity of the update source need explicit treatment in a real protocol.

Return to the task

Chapter 8 · Understand TCP as a reliable byte stream

Solution 8.1

There is no guaranteed message count. It may return part of the first message, exactly one, both, or another available prefix. The application must frame and accumulate data. Tests should feed the same logical messages through different chunk boundaries so correctness does not depend on a fortunate local packet layout.

Return to the task

Solution 8.2

The result is uncertain. The server may never have received the request, may be processing it, or may have completed it before the response was lost. Reconciliation or an application idempotency key is needed before retrying blindly. TCP’s reliable byte delivery does not provide exactly-once business operations across a broken connection.

Return to the task

Chapter 9 · Use TLS for confidentiality and server identity

Solution 9.1

The application’s object-level authorization failed. TLS protects the communication channel and can authenticate the server, but the service must still check whether the signed-in account may access user 13. Server-side access checks must not rely on the UI hiding a link.

Return to the task

Solution 9.2

A valid chain alone does not establish that the peer is authorized for the intended hostname. Accepting any trusted certificate would allow an unrelated certificate holder to impersonate other names. Correct the endpoint or deploy an appropriate certificate; do not remove hostname validation to make the error disappear.

Return to the task

Chapter 10 · Read HTTP requests, responses, caches, and versions

Solution 10.1

The cache can return one learner’s private representation to another. The service must deliberately define storage and variation rules and avoid public reuse where inappropriate. Authentication alone does not automatically configure every cache correctly. Test two accounts against the same route and inspect the actual cache behavior, not only application code.

Return to the task

Solution 10.2

No. HTTP/3 changes the transport mapping and connection behavior, while the slow database query remains application work. Profile DNS, connection setup, TLS, server processing, and transfer separately. A protocol upgrade may help particular loss or concurrency workloads, but it cannot eliminate unrelated computation.

Return to the task

Chapter 11 · Build a bounded TCP protocol on localhost

Solution 11.1

read_line raises EOFError because the protocol requires a newline delimiter and the peer closed before providing it. Treating the accumulated bytes as a valid request would silently change the protocol. A production service can log the framing failure without logging secrets and close the connection according to its policy.

Return to the task

Solution 11.2

Cover an empty line, a valid PING line, a delimiter exactly at the 64-byte bound, 64 bytes without a delimiter, EOF before a delimiter, invalid ASCII at the decoding boundary, and multiple frames arriving together. Use a fake socket returning chosen chunks for deterministic parser tests, then use the loopback exchange for integration. The byte-at-a-time reader deliberately leaves following bytes for later reads.

Return to the task

Chapter 12 · Design network trust and observability deliberately

Solution 12.1

It proves only that a connection reached a listener. The API must authenticate the caller and verify ownership or an explicit permission for the target progress record. Requests can be crafted outside the website UI. Enforce the check on the service handling the update, including every alternate route to the same data.

Return to the task

Solution 12.2

No. The retry policy can outlive the caller’s useful deadline before adding DNS or other overhead. Reduce attempts or per-attempt time, pass the remaining deadline downward, and stop work when it is no longer useful. Retrying faster without considering operation safety can also duplicate side effects or overload the dependency.

Return to the task

Chapter 13 · Diagnose by narrowing the failing stage

Solution 13.1

No. Inspect the requested path, filename, server working directory, and the files actually being served. The 404 is evidence that the HTTP server handled the request but did not find the target. Resetting a router changes unrelated state and destroys useful experimental control.

Return to the task

Solution 13.2

Investigate server queueing, worker limits, expensive handlers, and dependency wait time, while keeping loss and client behavior as alternatives to test. Compare stage timings and server-side observations under controlled concurrency. Do not infer that buying a faster access link will fix a server queue merely because the user perceives delay in a browser.

Return to the task

Chapter 14 · Capstone: make a local learning client predictable

Solution 14.1

A per-read two-second timeout never expires if each next byte arrives after one second, so the whole operation can last indefinitely. Store deadline = monotonic() + budget, calculate remaining = deadline - monotonic() before each read, reject when it is nonpositive, and set the operation timeout to the remaining time. Test this with a controlled slow sender rather than an uncontrolled external service.

Return to the task

Solution 14.2

Accept the lab when all valid and invalid request cases have deterministic results, size/deadline limits are tested, resources close, and an experiment report reproduces the behavior. State that remote identity, authorization, encryption, persistence, and large-scale concurrency remain outside scope. A production design needs those requirements examined independently, plus maintained protocol libraries and operational monitoring.

Return to the task

Retrieve before you review

Final knowledge check

Choose one answer for each question and write a short reason. Use the explanation to find the assumption or misconception behind an error.

  1. 1. A complete HTTP 404 response is strongest evidence of what?

    1. The intended file exists
    2. An HTTP endpoint answered the request
    3. Every route on the Internet is healthy
    4. The user is authorized for all files
    Check answer and reasoning
  2. 2. What is the serialization delay for 1,000 bytes on an 8-Mbit/s link, ignoring overhead?

    1. 1 ms
    2. 8 ms
    3. 125 ms
    4. 1 second
    Check answer and reasoning
  3. 3. For a remote destination, the first local frame normally targets which link-layer address?

    1. The remote server’s unchanged MAC
    2. Any broadcast address on Earth
    3. The local next-hop gateway’s MAC
    4. The DNS root’s MAC
    Check answer and reasoning
  4. 4. How many total IPv4 addresses are in a /27 block?

    1. 27
    2. 30
    3. 64
    4. 32
    Check answer and reasoning
  5. 5. Which matching prefix normally wins a forwarding lookup?

    1. The most specific matching prefix
    2. The oldest route regardless of prefix
    3. The longest domain name
    4. The route with the smallest printed address
    Check answer and reasoning
  6. 6. Why can one resolver still return an old record after an authoritative change?

    1. DNS permanently freezes records
    2. The old cached record may still be within its permitted lifetime
    3. TLS prevents changes
    4. An A record controls every application cache
    Check answer and reasoning
  7. 7. Which property does UDP itself supply?

    1. Guaranteed delivery
    2. Exactly-once processing
    3. Datagram boundaries
    4. Automatic business-level retries
    Check answer and reasoning
  8. 8. A TCP sender makes two writes. What can a receiver assume about read boundaries?

    1. Every read equals one write
    2. Every read contains both writes
    3. The second write is discarded
    4. No write-to-read message-boundary correspondence is guaranteed
    Check answer and reasoning
  9. 9. HTTPS is working, but a user can access another account by changing an ID. What failed?

    1. Application authorization
    2. Packet serialization
    3. The IP address format
    4. The definition of a port
    Check answer and reasoning
  10. 10. What is a necessary question before caching personalized responses?

    1. Can the cache ignore identity?
    2. Which identity and variation rules keep representations separate?
    3. Can every response live forever?
    4. Can status codes be removed?
    Check answer and reasoning
  11. 11. recv returns empty bytes while a required newline has not arrived. What does the reader know?

    1. A complete empty message arrived
    2. The peer is guaranteed to retry
    3. The sending side closed before this frame completed
    4. The message is valid UTF-8
    Check answer and reasoning
  12. 12. Why does a fresh timeout for every received byte fail to impose a total deadline?

    1. Bytes cannot arrive slowly
    2. Timeouts only work for DNS
    3. TCP ignores clocks
    4. A peer can keep each read below the timeout indefinitely
    Check answer and reasoning
  13. 13. A connection is quick but first-byte time rises under load. What is a useful next step?

    1. Measure server queueing and dependency work
    2. Reset every router immediately
    3. Assume DNS is always wrong
    4. Disable certificate validation
    Check answer and reasoning
  14. 14. A request timed out before its response. What is the safest general conclusion about a side effect?

    1. It definitely never happened
    2. Its outcome may be uncertain and needs reconciliation or a safe retry contract
    3. It always happened twice
    4. The transport can prove the database state
    Check answer and reasoning

Assessment explanations

1. Answer B

An HTTP endpoint answered the request

An HTTP response shows that an HTTP-speaking endpoint handled the exchange. The missing resource may be an application routing or deployment issue.

Revisit the chapter · Return to the question

2. Answer A

1 ms

The message is 8,000 bits. Divide by 8,000,000 bits/s to obtain 0.001 s, or 1 ms.

Revisit the chapter · Return to the question

3. Answer C

The local next-hop gateway’s MAC

IP identifies the end destination while the current frame reaches a local next hop. Routers rebuild link framing as needed.

Revisit the chapter · Return to the question

4. Answer D

32

Five host bits remain, giving 2^5 = 32 total addresses. Conventional host assignment rules are a separate question.

Revisit the chapter · Return to the question

5. Answer A

The most specific matching prefix

Longest-prefix matching chooses the matching route with the greatest prefix length, subject to the forwarding table’s applicable rules.

Revisit the chapter · Return to the question

6. Answer B

The old cached record may still be within its permitted lifetime

Record TTL and cache timing can permit reuse. Application and OS caches, address-family choices, and negative caching may also matter.

Revisit the chapter · Return to the question

7. Answer C

Datagram boundaries

UDP is message-oriented. Reliability, ordering, duplicate handling, and useful application completion require additional design.

Revisit the chapter · Return to the question

8. Answer D

No write-to-read message-boundary correspondence is guaranteed

TCP is a byte stream. The application must frame messages and tolerate splitting or coalescing.

Revisit the chapter · Return to the question

9. Answer A

Application authorization

A protected channel does not decide resource ownership. The service must authorize each operation.

Revisit the chapter · Return to the question

10. Answer B

Which identity and variation rules keep representations separate?

Cache keys, allowed storage, lifetime, and variation must preserve privacy and correctness.

Revisit the chapter · Return to the question

11. Answer C

The sending side closed before this frame completed

An orderly TCP close does not complete an application frame that requires a delimiter. The reader should apply its explicit incomplete-frame policy.

Revisit the chapter · Return to the question

12. Answer D

A peer can keep each read below the timeout indefinitely

A total deadline uses a monotonic end time and remaining budget; individual successful reads do not restart the overall budget.

Revisit the chapter · Return to the question

13. Answer A

Measure server queueing and dependency work

Stage-specific evidence suggests investigating service waiting or work while testing alternative causes. Random configuration changes do not isolate the bottleneck.

Revisit the chapter · Return to the question

14. Answer B

Its outcome may be uncertain and needs reconciliation or a safe retry contract

A response can be lost after a side effect. Application identity, idempotency, or status reconciliation is needed.

Revisit the chapter · Return to the question

Glossary

A record
A DNS record containing IPv4 address data. Chapter
AAAA record
A DNS record containing IPv6 address data. Chapter
ARP
An IPv4 local-link protocol for resolving a next-hop IP address to link-layer information. Chapter
Authoritative server
A DNS server serving authoritative data for a zone. Chapter
Authorization
A decision permitting a caller to perform an operation on a resource. Chapter
Bandwidth-delay product
Rate multiplied by round-trip time, estimating in-flight volume. Chapter
Cache validator
Metadata such as an ETag used to validate a stored representation. Chapter
Certificate
A signed binding of identity-related information and a public key under a trust model. Chapter
CIDR
Classless addressing notation using a prefix and its bit length. Chapter
Congestion control
Adjustment of sending in response to network conditions. Chapter
Deadline
An overall end time after which an operation is no longer allowed to keep waiting. Chapter
Encapsulation
Placing one layer’s data inside another layer’s formatted unit. Chapter
Flow control
Regulation of sending according to receiver capacity. Chapter
Framing
The application rule that identifies complete messages within bytes. Chapter
ICMP
Internet control and error-reporting protocol family. Chapter
Idempotency
A contract under which repetition has the intended same effect; details depend on the operation. Chapter
Latency
Elapsed delay for an operation or journey. Chapter
Loopback
A local host communication path such as 127.0.0.1 or ::1. Chapter
MAC address
A link-layer address used on an applicable local network. Chapter
MTU
Maximum transmission unit supported by a link without link-specific fragmentation. Chapter
NAT
Translation of address information at a network boundary. Chapter
Packet
A bounded unit of data handled by a network layer. Chapter
Port
A transport-layer endpoint number within a protocol’s address space. Chapter
Protocol
Rules for exchanging and interpreting messages, including abnormal cases. Chapter
Recursive resolver
A DNS service that obtains answers on behalf of a requester. Chapter
Route
Forwarding information associating destinations with an outgoing path or next hop. Chapter
RTT
Round-trip time for a particular exchange. Chapter
Serialization delay
Time to transmit a unit’s bits at a given link rate. Chapter
Subnet
A configured address-prefix range used in local network organization. Chapter
Switch
A device that forwards link-layer frames according to learned or configured information. Chapter
TCP
An ordered reliable byte-stream transport with connection state. Chapter
Throughput
Useful data successfully transferred per unit time. Chapter
TLS
A protocol for protected communication with defined peer-authentication mechanisms. Chapter
TTL
A context-dependent field: DNS cache lifetime or IPv4 hop-limiting value. Chapter
UDP
Datagram-oriented transport without built-in delivery or ordering guarantees. Chapter

Read and watch with a purpose

Reading and video library

Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.

  1. RFC 1122: Internet host communication requirements

    IETF · docs

    Historical architectural foundation; consult updates and errata, not an exhaustive current implementation checklist.

    https://www.rfc-editor.org/rfc/rfc1122.html
  2. RFC 826: Address Resolution Protocol

    IETF · docs

    Primary description of IPv4 address-to-link mapping on applicable local links.

    https://www.rfc-editor.org/rfc/rfc826.html
  3. RFC 1812: IPv4 router requirements

    IETF · docs

    Router forwarding, TTL, and error behavior; check later updates for deployment details.

    https://www.rfc-editor.org/rfc/rfc1812.html
  4. RFC 4861: IPv6 Neighbor Discovery

    IETF · docs

    Distinguishes IPv6 local neighbor discovery from IPv4 ARP.

    https://www.rfc-editor.org/rfc/rfc4861.html
  5. RFC 4632: Classless Inter-domain Routing

    IETF · docs

    Prefix aggregation and classless addressing background.

    https://www.rfc-editor.org/rfc/rfc4632.html
  6. RFC 3021: 31-bit prefixes on point-to-point links

    IETF · docs

    Explains a specific exception to a simplistic IPv4 host-count rule.

    https://www.rfc-editor.org/rfc/rfc3021.html
  7. RFC 4291: IPv6 addressing architecture

    IETF · docs

    IPv6 address forms, types, and scope; consult updates.

    https://www.rfc-editor.org/rfc/rfc4291.html
  8. RFC 3849: IPv6 documentation prefix

    IETF · docs

    Why 2001:db8:: addresses are used in examples.

    https://www.rfc-editor.org/rfc/rfc3849.html
  9. RFC 8200: IPv6 specification

    IETF · docs

    Primary IPv6 forwarding and fragmentation model.

    https://www.rfc-editor.org/rfc/rfc8200.html
  10. RFC 1191: IPv4 Path MTU Discovery

    IETF · docs

    Packet-size feedback concepts; later work extends discovery techniques.

    https://www.rfc-editor.org/rfc/rfc1191.html
  11. RFC 4443: ICMPv6

    IETF · docs

    IPv6 error reporting, including Packet Too Big.

    https://www.rfc-editor.org/rfc/rfc4443.html
  12. RFC 1034: DNS concepts and facilities

    IETF · docs

    Historical primary DNS hierarchy and resolver model; later standards extend it.

    https://www.rfc-editor.org/rfc/rfc1034.html
  13. RFC 1035: DNS implementation and specification

    IETF · docs

    Record and message details; consult updates.

    https://www.rfc-editor.org/rfc/rfc1035.html
  14. RFC 2308: DNS negative caching

    IETF · docs

    Why absence answers can remain cached.

    https://www.rfc-editor.org/rfc/rfc2308.html
  15. RFC 768: UDP

    IETF · docs

    The core datagram transport definition.

    https://www.rfc-editor.org/rfc/rfc768.html
  16. RFC 8085: UDP usage guidelines

    IETF · docs

    Application responsibilities, congestion considerations, and message sizing.

    https://www.rfc-editor.org/rfc/rfc8085.html
  17. RFC 9293: TCP

    IETF · docs

    TCP byte-stream and connection specification, published 2022.

    https://datatracker.ietf.org/doc/html/rfc9293
  18. RFC 5681: TCP congestion control

    IETF · docs

    Classic congestion-control concepts; modern deployments may use other specified algorithms.

    https://www.rfc-editor.org/rfc/rfc5681.html
  19. RFC 8446: TLS 1.3

    IETF · docs

    Protected-channel model and protocol details.

    https://www.rfc-editor.org/rfc/rfc8446.html
  20. RFC 9110: HTTP semantics

    IETF · docs

    Method, field, response, and identity-related HTTP semantics.

    https://www.rfc-editor.org/rfc/rfc9110.html
  21. RFC 9111: HTTP caching

    IETF · docs

    Freshness, validation, storage, and cache variation.

    https://www.rfc-editor.org/rfc/rfc9111.html
  22. RFC 9112: HTTP/1.1

    IETF · docs

    Message framing details; use an established parser.

    https://www.rfc-editor.org/rfc/rfc9112.html
  23. RFC 9113: HTTP/2

    IETF · docs

    HTTP/2 framing and stream concepts.

    https://www.rfc-editor.org/rfc/rfc9113.html
  24. RFC 9114: HTTP/3

    IETF · docs

    How HTTP maps onto QUIC.

    https://www.rfc-editor.org/rfc/rfc9114.html
  25. RFC 9000: QUIC

    IETF · docs

    Transport streams, flow control, and migration concepts.

    https://www.rfc-editor.org/rfc/rfc9000.html
  26. Python 3.11 socket reference

    Python Software Foundation · docs

    Socket operations and platform-specific details for the local labs.

    https://docs.python.org/3.11/library/socket.html
  27. Python 3.11 ipaddress reference

    Python Software Foundation · docs

    Validate address arithmetic and prefix membership.

    https://docs.python.org/3.11/library/ipaddress.html
  28. Python 3.11 ssl reference

    Python Software Foundation · docs

    Maintained TLS client contexts and validation behavior.

    https://docs.python.org/3.11/library/ssl.html
  29. Python 3.11 http.server reference

    Python Software Foundation · docs

    A local teaching server, explicitly not recommended as a production server.

    https://docs.python.org/3.11/library/http.server.html
  30. Python 3.11 time reference

    Python Software Foundation · docs

    Monotonic timing for deadline calculations.

    https://docs.python.org/3.11/library/time.html
  31. curl official manual

    curl project · docs

    Request options, error handling, and cumulative timing variables; options depend on installed version.

    https://curl.se/docs/manpage.html
  32. MIT Computer System Engineering, Spring 2018

    MIT OpenCourseWare · Watch / course

    Structured university networking and systems course with lecture material and activities.

    https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/
  33. Stanford CS144 networking lectures

    Stanford University · Watch / course

    Course lectures, resources, and hands-on Internet systems assignments; choose the stated course edition.

    https://cs144.github.io/

Continue on OpenLearning

Use the subject library to move between reading, practice, study material, and the wider topic map.

Make the explanation better

If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.

Editable book sources on GitHub

Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.