The Application Layer

Learn how the internet's application protocols work and why they are designed the way they are. Compare client-server and peer-to-peer designs and choose between TCP and UDP. Read HTTP messages, explain cookies, caching, HTTP/2 and HTTP/3 over QUIC, and trace DNS lookups and email delivery. Calculate peer-to-peer distribution times, explain adaptive video streaming and content distribution networks, and write simple UDP and TCP client and server programs in Python.

IntermediateLesson 2 of 8 in Computer Networks Course

What you will learn

  1. Compare client-server and peer-to-peer designs, describe how application processes exchange messages through sockets, and match an application's needs to the services that TCP and UDP offer.
    • Compare client-server and peer-to-peer architectures
      Describe how each architecture assigns roles to hosts, why peer-to-peer designs scale with their users, and what challenges each design brings.
    • Describe how processes communicate and choose a transport service
      Explain sockets, process addressing and what an application-layer protocol defines, and decide whether an application should run over TCP or UDP.
  2. Read and reason about HTTP messages and connections, explain how cookies and caches work, and describe what HTTP/2 and HTTP/3 change in the way messages travel.
    • Read HTTP messages and compare connection types
      Interpret HTTP requests and responses, and calculate how persistent and non-persistent connections affect the time needed to load a page.
    • Explain how cookies and web caches work
      Describe how cookies let websites recognize users over stateless HTTP, and calculate how a caching proxy and conditional requests reduce delay and traffic.
    • Explain how HTTP/2 and HTTP/3 with QUIC speed up the web
      Describe head-of-line blocking, and explain how HTTP/2 framing and HTTP/3 over QUIC reduce delays while the meaning of HTTP messages stays the same.
  3. Trace a name lookup through the DNS hierarchy, read DNS records and messages, and explain how caching and a distributed design keep DNS fast and resilient.
    • Trace a name lookup through the DNS hierarchy
      Describe the services DNS provides and the roles of root, top-level domain, authoritative and local DNS servers, and follow the queries of a lookup step by step.
    • Read DNS records and messages
      Interpret the common resource record types, follow how records link the levels of the hierarchy, and read DNS queries, replies and their security weaknesses.
  4. Trace a message from sender to recipient through SMTP, read mail transfer dialogues and message formats, and explain how mail access protocols let users read their mail.
    • Trace a message through SMTP mail transfer
      Describe the parts of the email system, follow an SMTP dialogue between mail servers, and explain how mail is submitted and how forged senders are detected.
    • Explain message formats and mail access protocols
      Read the header and MIME structure of an email message, and compare IMAP, POP3 and webmail as ways of reading mail.
  5. Calculate why peer-to-peer file distribution scales, explain how BitTorrent shares a file, and describe how adaptive streaming and content distribution networks deliver video to millions of viewers.
    • Calculate P2P distribution time and explain BitTorrent
      Compare the minimum time to distribute a file with a server and with peer-to-peer, and explain how BitTorrent's chunks, rarest-first requests and tit-for-tat trading work.
    • Explain adaptive video streaming over HTTP
      Relate video bit rates to network throughput, and explain how DASH clients choose segments to keep playback smooth.
    • Explain how content distribution networks deliver content
      Describe why content providers use CDNs, compare ways of placing CDN servers, and follow how DNS directs a request to a nearby CDN server.
  6. Use Python's socket module to build UDP and TCP clients and servers, and explain how each program's behavior follows from the transport service underneath it.
    • Build a UDP client and server
      Write and explain a UDP client-server pair in Python, including addressing, encoding, timeouts and the limits of datagram delivery.
    • Build a TCP client and server
      Write and explain a TCP client-server pair in Python, handle TCP's byte stream correctly, and use a socket to speak HTTP by hand.

Application Layer study guide

6 chapters

1

Application design and transport services

Networked programs need a plan for who communicates with whom and a service that carries their data. A browser fetching a file and a game sending position updates can share the same internet while making different design choices. Follow an exchange from the processes at its ends through their sockets, then compare what TCP, UDP and secure transports offer for reliability, timing, throughput and protection.

1.1 Where application programs run

A network application consists of programs running on end systems: phones, laptops and servers. Their processes exchange messages across the network. Routers and switches forward the packets; they do not need a new application program installed whenever someone creates a new service.

Two ways to assign the work

An application architecture describes how the application divides work among hosts. It is separate from the network's layered architecture. The developer chooses where programs run while relying on the existing network to connect them.

In a client-server design, clients contact an always-on server at a known address. A browser requests a document from a web server, which returns the document. Other browsers do not need to be online for that exchange to work. A popular service can spread its server role over thousands of machines in data centers; one public name can represent that group. Equipment, power, cooling and internet connections all cost money.

A peer-to-peer, or P2P, design lets user devices exchange data directly. A peer can request a file chunk and also upload chunks it already holds. Peers may disconnect or change addresses, so the application must find available peers and keep operating as membership changes.

DesignWho provides the content?What happens as users join?
Client-serverDedicated server hostsMore requests reach the service's servers.
P2PParticipating user hostsDemand grows, and peers contribute upload capacity.
Follow one exchange

Suppose a research group distributes a large data set. In a client-server design, every researcher downloads a copy from the group's server. Ten new researchers mean ten more copies for that server to upload. In a P2P design, researchers who already hold some chunks send those chunks to newcomers. Each joining researcher can add capacity as well as demand. This is self-scaling: the application's resources grow with participation.

Self-scaling still depends on useful contributions. A peer with a slow upload link adds less capacity than one with a fast link. Many residential links are asymmetric: downloading is faster than uploading. A peer that disconnects contributes nothing while offline. P2P software must also protect participants against untrusted peers and encourage users to upload instead of only taking data.

Central coordination and direct transfer

A hybrid design combines server coordination with P2P data transfer. A BitTorrent tracker tells a peer about other peers; it does not have to send the file itself. Similarly, a calling service can locate participants through a server, let their devices exchange media directly, and use a relay when a direct path is unavailable. Classify the path carrying the data separately from the path that sets it up.

The words client and server also describe roles in an individual exchange. If peer Mira initiates a request to peer Leo, Mira is the client and Leo is the server for that exchange. They can reverse roles a moment later. P2P removes dependence on dedicated content servers; it does not remove the initiating and responding roles.

Key Takeaways

  • Application programs run on end systems; the network core forwards their packets.
  • Client-server designs place service capacity in dedicated hosts.
  • P2P participants add upload capacity as well as demand.
  • A hybrid can use a central directory while peers transfer the content.
  • Client and server roles depend on who initiates each exchange.

1.2 Sockets, addresses and transport choices

A running application program is a process. Processes on different hosts exchange messages through sockets, the software interfaces between the application and transport layers. Application code decides what the message means; the transport service carries its bytes or datagrams.

Find the receiving process

An IP address identifies a host, but the host can run many services. A port number identifies a transport endpoint on it. To contact an HTTPS service at 203.0.113.10, a client normally targets port 443. Its own operating system usually assigns a temporary, or ephemeral, source port.

Ports are 16-bit values, from 0 through 65,535. System ports occupy 0–1023, registered ports 1024–49,151, and dynamic ports 49,152–65,535. Common service ports include HTTP 80, HTTPS 443, SMTP transfer 25 and DNS 53. A port is part of addressing, not a statement that the traffic is encrypted or trustworthy.

Agree on the messages

An application-layer protocol defines message types, syntax, semantics and exchange rules. Types distinguish a request from a response. Syntax describes fields and separators. Semantics tells each participant what those fields mean. Exchange rules determine when a process sends a message and how the receiver responds. Public specifications, often RFCs, let programs written by different developers communicate.

A protocol is one component of an application. The web also needs browsers, servers and documents. Defining HTTP alone does not build a browser or decide how its interface looks.

Match the service to the need

Consider four needs: correct delivery, enough throughput, acceptable delay, and security. An email attachment requires every byte. A voice call can tolerate some lost media but suffers if old audio arrives too late. A stored video needs sustained throughput near its encoded bit rate, while an elastic download can use whatever rate is available.

ServiceWhat the application receivesWhat it still must handle
TCPA reliable, ordered byte stream after connection setupMessage framing, security and variable delay or throughput
UDPSeparate datagrams without connection setupLoss, duplication, ordering and any required reliability

TCP includes flow control to protect the receiver and congestion control to reduce overload in the network. It supplies no minimum bandwidth or delivery deadline. UDP itself adds neither reliability nor congestion control. Choosing it does not remove congestion from the path.

For example, a game sending positions 30 times each second produces a fresh update about every 33 ms. It may use UDP so a lost update can be replaced by a newer one without waiting for that update to be retransmitted. The game's chat still needs reliable delivery, whether through TCP or reliability added by its own protocol.

Add security to the stack

Neither bare TCP nor bare UDP encrypts application data. HTTP/1.1 and HTTP/2 commonly use TLS over TCP for HTTPS. TLS adds confidentiality, integrity and server authentication. HTTP/3 uses QUIC over UDP; QUIC supplies reliability, congestion control and built-in TLS 1.3. Stored video delivered with HTTP therefore uses TCP or QUIC, while interactive calls often carry media over UDP.

Key Takeaways

  • An IP address and port identify where a process receives network traffic.
  • Application protocols define types, syntax, semantics and exchange rules.
  • TCP provides reliable ordered bytes, with no guaranteed rate or deadline.
  • UDP preserves datagrams but leaves reliability to higher layers.
  • Neither TCP nor UDP encrypts data by itself.
  • HTTP/3 obtains reliable, secure streams from QUIC over UDP.
2

How HTTP delivers web content

A page load combines message formats, connection setup and requests for several objects. Its behavior also depends on whether the browser can reuse a connection or response, and whether the site needs to recognize the visitor. Read the visible HTTP exchange first, calculate its main delays, then follow how cookies, caching and newer HTTP transports change the work required to deliver the page.

2.1 HTTP messages and connection timing

A web page is usually several objects, each with its own URL. The base HTML names images, scripts and other files. In https://www.example.org/docs/intro.html, the scheme is https, the host is www.example.org, and the path is /docs/intro.html.

Read a request and response

HTTP follows request-response exchanges. An HTTP/1.1 request starts with a method, path and version:

GET /docs/intro.html HTTP/1.1
Host: www.example.org
Connection: close

The request line and header lines use CRLF endings. A blank line ends the headers, and an optional body follows. Host is required in HTTP/1.1 because several sites can share one server address. Connection: close requests closure after the response.

GET retrieves an object. HEAD requests its response headers without the body. POST sends data in a request body; a GET can also carry form values in its URL query string. PUT stores an object at a specified URL, and DELETE removes one.

The response begins with a status line such as HTTP/1.1 200 OK, followed by headers, a blank line and the body. Content-Type identifies the representation; Content-Length gives its byte length. Status classes are 1xx information, 2xx success, 3xx redirection, 4xx client error and 5xx server error. A 301 points to a new URL in Location; 304 permits reuse of a cached copy. A 404 means the server replied that the requested object was not found, not that the server was unreachable. Other useful codes include 400, 500 and 505.

HTTP is stateless: each request can be understood without earlier requests. A website can still keep login or cart state above HTTP. An ordinary repeated GET can return the object again, while a conditional request can validate a saved copy.

Count the round trips

For one object over a new TCP connection, allow one RTT for connection setup and one for the request and start of the response. Then add object transmission time. With RTT 30 ms, size 500 kB and rate 50 Mbps:

Ttransmit=500,000×850,000,000=0.08 s

The total is 60 ms plus 80 ms, or 140 ms. This model ignores DNS, TLS and processing time. A full TLS 1.3 handshake over the new TCP connection adds another RTT.

Reuse or reopen the connection

A non-persistent connection carries one object. A persistent connection can carry later requests without another TCP setup. Persistence is the HTTP/1.1 default, though idle connections eventually close.

For one HTML object and eight small images, RTT 20 ms, and negligible transmission times:

Fetch patternRound tripsTime
New connection for each object, sequentially18360 ms
HTML first, then eight new connections in parallel480 ms
One persistent connection, sequential requests10200 ms
One persistent connection, eight pipelined image requests360 ms

The image requests depend on receiving the HTML. Even with parallel fetching, they cannot start before their URLs are known. Count those dependency stages before counting handshakes. HTTP/1.1 browsers commonly use several connections per host; pipelining is a timing model, not a requirement for persistence.

Key Takeaways

  • A page load includes the HTML and its referenced objects.
  • HTTP/1.1 separates its start line, headers and optional body with line endings and a blank line.
  • For a new TCP connection, one object costs about two RTTs plus transmission time before TLS costs.
  • Persistence saves repeated connection setup.
  • Parallel requests still wait until the HTML reveals their URLs.
  • A 404 response shows that an HTTP server answered.

2.2 Recognizing users and reusing responses

HTTP requests stand on their own, yet a store can remember a cart. A browser can also reuse an image instead of downloading it again. Cookies support recognition across requests; caches support reuse of responses.

Follow a cookie

On a first visit, shop.example.com creates a database entry for a visitor and returns Set-Cookie: id=1678. The browser stores that value. Later matching requests include Cookie: id=1678, allowing the server to look up the cart. The cookie is data, not executable code, and the cart itself can remain in the server's database.

Cookie attributes control its use. Expires or Max-Age sets a lifetime; a cookie without either is a session cookie. Domain and Path restrict matching requests. Secure restricts sending to HTTPS, HttpOnly prevents access through page scripts, and SameSite controls sending in cross-site contexts. Session restoration can retain session cookies when a browser restores a previous session.

First-party cookies belong to the visited site. An embedded third-party service can use cookies across different sites to recognize a browser. Safari blocks third-party cookies by default; Firefox partitions them by site; Chrome provides user controls and blocks them in Incognito mode. European Union rules require consent for cookies that are not strictly necessary to provide a requested service.

Follow a cached request

A web cache stores HTTP responses. A browser has its own cache. A caching proxy sits between clients and origin servers: it serves a cache hit directly, or fetches, stores and forwards a response on a miss. It acts as a server toward the browser and as a client toward the origin. A proxy can exist without caching.

A nearby hit reduces delay, origin load and access-link traffic. For 90 requests per second averaging 1 Mbit each, the offered traffic is 90 Mbps. On a 100 Mbps access link, the traffic intensity is 0.9, where queues can become large. A 40% hit rate leaves 60% crossing the link: 54 Mbps and intensity 0.54. With hits taking 10 ms and misses 200 ms, the mean response time is:

T=0.4(10)+0.6(200)=124 ms

This traffic calculation assumes the same mean object size for the hit and miss groups. A hit rate measured by request count alone need not equal the fraction of bytes saved when object sizes differ.

Check freshness before reuse

A conditional GET sends If-Modified-Since with a saved modification date, or If-None-Match with a saved ETag. An unchanged object gives 304 Not Modified without an object body. The cache reuses its copy. A changed object gives 200 OK with the replacement. Validation saves body transmission, but still makes a round trip to the origin.

Response directiveMeaning
max-age=3600A copy can remain fresh for 3,600 seconds.
no-cacheStore it if allowed, but validate before reuse.
no-storeDo not store the response.
privateA private cache may store it; shared caches may not.

A shared proxy normally cannot inspect the contents of an HTTPS connection passing through it. Browser caches and CDN servers serving on a site's behalf can cache at the endpoints where those responses are available in readable form.

Key Takeaways

  • Cookies let a server recognize a browser across independent HTTP requests.
  • Cookie attributes control lifetime, scope and access.
  • A caching proxy has both client and server roles.
  • Cache hits can lower delay and reduce access-link traffic.
  • A 304 response validates a saved object without resending its body.
  • no-cache requires validation; no-store forbids storage.
  • HTTPS limits what an ordinary shared proxy can cache.

2.3 Frames, streams and HTTP/3

HTTP versions keep the meanings of methods, statuses, fields and URLs. A 404 still means the requested resource was not found. What changes is how requests and responses travel: HTTP/1.1 uses text messages, while HTTP/2 and HTTP/3 use binary framing.

Let small responses make progress

On an HTTP/1.1 connection, ordered responses can make a small object wait behind a large one. This is application-level head-of-line blocking. Opening several TCP connections reduces that waiting but costs extra setup and gives the page several competing congestion-controlled connections.

HTTP/2 divides messages into frames and assigns each request-response exchange a stream. The sender interleaves frames from different streams on one TCP connection. Header compression, called HPACK, reduces repeated field data. Priorities can guide which responses receive attention first.

For a simplified comparison, one large response has 1,000 frames and eight small ones have two frames each. Send one frame per time slot. Sending the large response first makes small responses finish at slots 1,002 through 1,016, with a mean of 1,009. Sending one frame from each unfinished stream in turn lets the small responses finish in slots 11 through 18, with a mean of 14.5. The large response finishes at slot 1,016. Interleaving changes completion times without increasing the link's transmission rate.

HTTP/2 also specified server push, which sends content before a request. Major browsers have disabled it. A 103 Early Hints response instead points out resources so the browser can start requesting them.

Find the remaining blocking point

TCP delivers one ordered byte stream. If bytes are missing, later bytes wait for recovery even when they contain another HTTP/2 stream's frames. HTTP/2 removes response-order blocking but retains this transport-level blocking.

HTTP/3 maps HTTP onto QUIC, a transport running over UDP, and compresses headers with QPACK. QUIC supplies reliable streams, flow and congestion control, and TLS 1.3 security. Each stream has its own delivery order. Missing data on one stream does not, by itself, prevent delivery of already received data on another. Shared congestion control and application dependencies can still affect several streams.

QUIC uses connection IDs so a connection can survive an IP address change, such as moving from Wi-Fi to cellular service. Its implementation can be updated with an application library, avoiding the slow deployment path of changes to TCP in operating systems and middleboxes.

Compare a fresh connection

With RTT 50 ms and no DNS or processing cost, TCP plus TLS 1.3 takes two RTTs before the first HTTP/2 request leaves. A first response begins after about 150 ms. QUIC combines transport and security setup into one RTT, so an HTTP/3 response can begin after about 100 ms. Resumed QUIC connections can use 0-RTT data, but replay risk limits what requests can safely be sent early.

Browsers can discover HTTP/3 through Alt-Svc or DNS HTTPS records. If UDP is blocked, they can fall back to HTTP over TCP. HTTP/3 remains reliable because QUIC provides reliability above UDP.

Key Takeaways

  • HTTP versions preserve shared message meanings.
  • HTTP/2 interleaves streams on one TCP connection.
  • TCP loss can still block all HTTP/2 streams on that connection.
  • QUIC provides independent ordered streams and built-in security over UDP.
  • QUIC reduces fresh connection setup and supports address changes through connection IDs.
3

How DNS finds services

Names hide the changing locations of internet services. Before a browser or mail server contacts a destination, DNS can supply an address, an alias or a mail-server name. Follow a resolver through the distributed hierarchy, then inspect the records and message fields it exchanges. Cached answers make this process fast, while their lifetimes explain why a changed address may take time to reach every user.

3.1 A DNS lookup from cache to authority

A name such as www.example.org is convenient for a person. A connection needs an IP address. The Domain Name System, or DNS, is both the distributed database of naming records and the application protocol used to query it. It normally uses port 53 and operates separately from HTTP.

Divide the naming work

Read www.example.org. from right to left: root, org, example, then www. The final dot represents the root and is usually omitted in everyday writing. A centralized server for every name would create a failure point, a traffic bottleneck and long paths for distant clients.

Root servers refer resolvers to top-level domain servers. TLD servers refer them to the authoritative servers for domains beneath the TLD. Authoritative servers publish the actual records for a domain. The root's 13 named server identities are replicated across many physical instances; 13 is not the number of machines supporting the world's DNS.

The host normally sends its question to a local resolver, provided by its organization, ISP or a public service. That resolver works on the host's behalf. It is not another level between the root and the TLD in the naming hierarchy.

Trace an empty-cache lookup

A campus laptop needs the IPv4 address of www.example.org:

  1. The laptop asks its local resolver for the final answer.
  2. The resolver asks a root server and receives a referral to .org servers.
  3. It asks a .org server and receives a referral to the authoritative servers for example.org.
  4. It asks an authoritative server and receives 203.0.113.25.
  5. It returns the address to the laptop.

There are four query-reply pairs, or eight messages. The host's request is recursive: obtain the answer for me. The resolver's queries are iterative: each contacted server answers from its knowledge or refers the resolver onward. The root is not fetching the web server's address on the laptop's behalf.

Reuse answers until their TTL ends

A resource record carries a time-to-live, or TTL, measured in seconds. Resolvers keep reusable records in caches until their permitted lifetime ends. They can cache referrals as well as final addresses. A remembered TLD or domain delegation lets a later lookup skip earlier steps. Operating systems and browsers may also have caches.

With a 2 ms RTT between host and resolver and a 30 ms RTT for each of three sequential hierarchy queries, the empty-cache lookup takes about 92 ms. A cached address at the resolver takes about 2 ms. The waiting times add because each referral supplies information needed for the next query.

Caching also delays changes. If a resolver cached an address with a one-hour TTL just before an update, it can keep returning the old address for the remaining lifetime. Lowering a TTL in advance of a planned change limits this overlap; changing the authoritative record alone does not replace every cached copy.

DNS does more than name-to-address lookup. It supports aliases, finds mail servers, and distributes load by returning several addresses for a service. Those roles explain why email delivery and CDN selection also depend on DNS.

Key Takeaways

  • DNS is a distributed database and an application-layer query protocol.
  • Root, TLD and authoritative servers divide responsibility by name.
  • A local resolver carries out the host's recursive request using iterative queries.
  • Cached records and referrals shorten later lookups.
  • TTL limits caching time, so address changes take time to spread.

3.2 Records, referrals and DNS replies

DNS stores resource records with a name, value, type and TTL. A type tells the resolver how to interpret the value. An address record, an alias and a mail-server record answer different questions about the same domain.

Read the record type
TypeWhat its value provides
AAn IPv4 address for a host name
AAAAAn IPv6 address for a host name
NSThe name of an authoritative server
CNAMEA canonical name for an alias
MXA mail server name with a preference number
TXTText, including mail authentication information
PTRA name for a reverse address lookup
SOAAdministrative information for a zone
HTTPSService information, including supported HTTP versions

For example, www.example.org. 3600 IN A 203.0.113.25 gives the owner name, TTL, internet class, type and address. An NS value is a name, not an address. A referral can include a separate A record supplying the name server's address, often called glue when needed to resolve the delegation.

A CNAME such as media.example.org pointing to edge.cdn.example.net leads the resolver to look up the target's address. An MX record instead directs mail delivery. With preferences 10 and 20, try the mail server with preference 10 first; a larger number does not mean higher priority.

Read the message around the records

Queries and replies share a format. The 12-byte header contains an identification number, flags and counts of entries in four sections. The reply copies the query's ID so the requester can match the exchange.

The question section names what was requested. The answer section holds matching records. The authority section can hold NS referrals, while additional supplies helpful records such as name-server addresses. In printed dig output, qr marks a reply, rd means recursion was requested and ra means recursion is available. NOERROR reports no DNS error; NXDOMAIN reports that the queried name does not exist. A no-error response can still lack a record of the requested type.

To publish a new domain, an owner registers it and supplies its authoritative server information. The parent delegation directs queries to those servers, which publish the domain's own host and mail records. Registering the name does not turn the registrar into the server holding every record.

Delivery and protection

Most small DNS exchanges use UDP port 53. A truncated UDP reply has its TC flag set; the resolver can retry over TCP port 53. TCP also supports zone transfers. DNS is therefore not restricted to UDP.

Classic DNS traffic exposes queried names to observers on its path. DNS over TLS or DNS over HTTPS encrypts the client-to-resolver exchange, commonly on ports 853 and 443 respectively. Encryption of that exchange and authenticity of a record are separate properties.

In cache poisoning, a resolver accepts a forged answer and later sends users to the wrong address. Unpredictable IDs and source ports make forged replies harder to match. DNSSEC adds signatures that support verification of record authenticity; it does not hide the query. Flooding can also make DNS servers unreachable. Replication and cached referrals reduce dependence on the root for every request, but failures at a widely used authoritative provider can still disrupt many sites.

Key Takeaways

  • Record types distinguish addresses, delegations, aliases and mail routing.
  • An NS record names a server; a separate address record locates it.
  • MX records with lower preference numbers are tried first.
  • DNS replies separate answers, authority information and additional records.
  • DNS can use TCP as well as UDP.
  • Encrypted DNS protects a path; DNSSEC authenticates signed records.
4

How email moves and stays available

An email can arrive while its recipient's phone is off because servers handle delivery and storage independently of user devices. Trace the transfer conversation, distinguish its delivery envelope from the fields shown to a reader, and inspect how attachments fit into a message. Then compare the access protocols that let a laptop, phone or browser retrieve mail and keep track of mailbox state.

4.1 SMTP delivery and the mail envelope

Email separates composing a message from delivering it. A user agent is the app or web page used to read and write mail. A mail server stores incoming mail in mailboxes and holds outgoing messages in a queue. SMTP transfers messages between systems.

Trace delivery after submission

Alice submits a message for Bob to her own server. That server looks up the MX records for Bob's domain, resolves the chosen server's address and opens a TCP connection to port 25. It pushes the message to Bob's server, which stores it in his mailbox. Alice's server is the SMTP client during that transfer, even though it serves Alice's user agent in another exchange.

If the destination is temporarily unavailable, the outgoing queue retains the message for retries. Alice's device can go offline while her server keeps working. After repeated failure, a non-delivery report can return to the envelope sender.

Read the conversation

SMTP uses text commands and numeric replies. Here is a shortened delivery exchange; C: and S: identify the two speakers and are not transmitted as part of each command.

S: 220 mail.example.net ready
C: EHLO mail.example.org
S: 250 mail.example.net
C: MAIL FROM:<alice@example.org>
S: 250 OK
C: RCPT TO:<bob@example.net>
S: 250 OK
C: DATA
S: 354 Send message
C: From: Alice <alice@example.org>
C: To: Bob <bob@example.net>
C: Date: Tue, 03 Mar 2026 10:02:44 +0100
C: Subject: Lab report
C:
C: The report is ready.
C: .
S: 250 Message accepted
C: QUIT
S: 221 Closing

EHLO introduces the sending host. MAIL FROM sets the envelope sender; each RCPT TO names an envelope recipient. DATA begins the message, and a line containing only a period ends it. One connection can carry more than one message. Reply classes distinguish success (2xx), a request for further input (3xx), temporary failure (4xx) and permanent failure (5xx). A 4xx response calls for later retry; a 5xx failure needs different handling, often a bounce.

Keep delivery addresses separate from displayed fields

The envelope controls routing. The From: and To: fields inside the message are displayed to the reader. They can differ from the envelope. A Bcc recipient can appear in RCPT TO without appearing in the visible message headers. Replying to a message and reporting a delivery failure need not use the same address.

A user normally submits through authenticated SMTP on port 587 with STARTTLS, or port 465 with TLS from the start. Server-to-server transfer normally uses port 25 and can negotiate STARTTLS. Submission and transfer have different roles even when both use SMTP. HTTP generally pulls requested objects; SMTP pushes a prepared message.

Check the sender's domain

A visible From: field is easy to forge. SPF checks whether the sending host is authorized for the envelope domain. DKIM verifies a message signature using a public key published in DNS. DMARC connects a successful SPF or DKIM result to the visible From domain through domain alignment and publishes a policy for failures. Passing SPF for an unrelated envelope domain alone does not validate the visible sender.

Key Takeaways

  • SMTP pushes messages over TCP between mail servers.
  • Queues let servers retry while user devices are offline.
  • The SMTP envelope controls delivery; message headers control what readers see.
  • Submission commonly uses authenticated SMTP on port 587 or 465.
  • Temporary and permanent SMTP failures require different responses.
  • DMARC requires an aligned SPF or DKIM pass, not merely any SPF pass.

4.2 Message content and reading a mailbox

Mail transfer, message content and mailbox access are separate parts of email. SMTP moves a message to a mail server. The message has its own header-and-body format, and a recipient later accesses the stored mailbox through another protocol.

Read the message itself

A message begins with fields such as From:, To:, Date:, Subject: and Message-ID:. A blank line separates these headers from the body. They remain part of the stored message; SMTP's MAIL FROM and RCPT TO commands do not become message headers.

The basic format uses text lines. MIME, Multipurpose Internet Mail Extensions, describes richer content with extra fields. Content-Type: text/plain; charset=UTF-8 describes plain text and its character encoding. image/jpeg identifies an image. multipart/mixed describes multiple parts, separated by a boundary string, such as a text note followed by an attachment. Each part can have its own content type and transfer encoding.

Content-Transfer-Encoding describes how a part is represented for transfer. Base64 turns each group of three bytes into four ASCII characters. For a 3 MB attachment, 3,000,000 bytes become 4,000,000 characters before line breaks and message headers. The encoding adds about one third to the size. A server's total message-size limit therefore cannot be compared with the raw attachment size alone. Quoted-printable is another encoding suited to mostly readable text.

Choose a mail access protocol

The recipient's server can receive mail while the recipient's devices are offline. When the recipient returns, a mail access protocol lets a client retrieve stored messages.

Access methodWhere mailbox state livesEffect across devices
IMAPMessages, folders and flags stay on the server.Devices can share the same organization and read state.
POP3A client downloads messages and can delete them from the server.Download-and-delete can make mail unavailable to another device.
WebmailA browser interacts with the mail service through HTTPS.The service manages the mailbox behind the web interface.

IMAP can fetch a message's headers or selected parts without downloading every attachment. It commonly uses port 143 with STARTTLS or port 993 with TLS from the start. POP3 commonly uses port 110 or TLS on 995. Its deletion marks take effect when the session completes normally. Download-and-keep leaves copies on the server, but POP3 does not provide IMAP's server folders and shared flags.

Suppose Bob checks mail on a laptop before leaving home, then on a phone. If the laptop uses POP3 download-and-delete, the phone may find an empty server mailbox. With IMAP, marking a message read on the laptop changes server state that the phone can also see. The difference is mailbox synchronization, not SMTP delivery.

Follow a webmail message beyond the browser

A browser submits or reads mail using HTTPS. The webmail provider still uses SMTP to move mail to another domain's server. A complete path can therefore be HTTPS from sender to provider, SMTP between providers, then IMAP or HTTPS at the receiving end. Calling a service webmail describes its user interface and browser connection, not every protocol used along the message's route.

Key Takeaways

  • Message headers belong to the message, separately from SMTP commands.
  • MIME describes content types, multipart boundaries and transfer encodings.
  • Base64 adds about one third to attachment data before other overhead.
  • IMAP synchronizes server-side messages, folders and flags.
  • POP3 download-and-delete can remove messages before another device reads them.
  • Webmail uses HTTPS at the browser and still relies on SMTP between mail servers.
5

Distributing files and streaming video

Large audiences create different bottlenecks for one server, a group of peers and a distributed set of caches. Start with the upload and download limits on file distribution, then examine how BitTorrent shares that work. For video, connect encoded rate and segment downloads to the playback buffer, and follow how a CDN places content and directs users toward servers that can deliver it efficiently.

5.1 File distribution and BitTorrent

Distributing a file means every recipient must obtain a complete copy. The bottleneck is not always the server: a slow downloader or insufficient total upload capacity can set the minimum time. The standard model assumes access links are the bottlenecks and the core has enough capacity.

Compare the lower bounds

Let the file contain F bits, with N recipients. The server uploads at us; peer i uploads at ui and downloads at di. The lowest peer download rate is dmin. Use matching units, such as Mbit and Mbps, so division produces seconds.

With client-server distribution, the server must send NF bits and the slowest peer must receive F bits:

Dcs≥max⁡{NFus,Fdmin}

For P2P, the server must introduce every bit at least once. Peers still have to download the file, and the whole system must upload enough data for all copies:

DP2P≥max⁡{Fus,Fdmin,NFus+∑iui}

Take the maximum, because all requirements must be met during the distribution. Adding the terms would incorrectly assume those upload and download activities occur one after another. These are lower bounds; protocol overhead, unavailable peers and other bottlenecks can make real transfers slower.

Work one comparison

For a 2 Gbit file, use 2,000 Mbit. Let server upload be 100 Mbps, the slowest download 20 Mbps, and each of 100 peers upload at 5 Mbps.

The client-server server term is 200,000 Mbit divided by 100 Mbps, or 2,000 s. The slowest download term is 100 s. Its bound is therefore 2,000 s.

For P2P, introducing the file takes at least 20 s. The slowest download still takes 100 s. Total upload capacity is 100 plus 500, or 600 Mbps; distributing 200,000 Mbit takes at least about 333 s. The P2P bound is about 333 s. With 1,000 peers, the client-server bound rises to 20,000 s, while the P2P bound is about 392 s. For equal peer upload rates, the total-capacity term approaches file size divided by one peer's upload rate as the peer count becomes large.

Trade chunks in BitTorrent

A torrent is a group sharing one file. Peers exchange chunks, discover neighbors through a tracker or distributed hash table, and can upload before finishing the download. A seeder has the complete file and continues sharing it.

Rarest first chooses a needed chunk held by the fewest neighbors, helping preserve chunks that could otherwise disappear when a peer leaves. It decides what to request. Tit-for-tat encourages useful exchange by favoring neighbors supplying data quickly; it decides whom to upload to.

In the original design, four interested neighbors are unchoked at a time, including one optimistic unchoke. The regular choice is reconsidered about every 10 s and the optimistic peer about every 30 s. That exploratory slot gives newcomers a way to get initial chunks and helps discover better partners. The tracker coordinates discovery; it is not the data source for every chunk.

Key Takeaways

  • Client-server distribution is limited by server upload and the slowest download.
  • P2P also depends on introducing the file and total system upload capacity.
  • Take the maximum of simultaneous constraints, not their sum.
  • P2P scales because new peers contribute upload capacity.
  • Rarest first selects chunks; tit-for-tat selects upload partners.
  • An optimistic unchoke gives new or unexplored peers a chance to exchange.

5.2 Adaptive streaming and buffer changes

A video consists of frames displayed over time. Compression removes repeated information within a frame (spatial redundancy) and across frames (temporal redundancy). The encoded result has a bit rate: the amount of video data needed for each second of playback.

Connect rate, size and playback time

A two-hour video at 5 Mbps contains 36,000 Mbit, or 4.5 GB. Multiply rate by duration to obtain bits, then divide by eight for bytes. An average path throughput below the selected video rate eventually drains any finite buffer during continued playback.

A player can start before downloading the whole video. It stores upcoming data in a buffer, measured here in seconds of playable video. Playback consumes that buffer while downloads replenish it. A larger starting buffer gives protection against throughput dips but increases startup delay.

Request one segment at a time

DASH, Dynamic Adaptive Streaming over HTTP, stores several encoded versions at different rates and cuts each into segments. A manifest lists available versions and segment URLs. The client requests a segment with HTTP GET and chooses a version again at the next segment boundary. HLS uses a similar approach with playlists.

The player makes the adaptation decision using measured throughput and buffer level. A high recent throughput estimate favors a higher rate; a low buffer calls for caution. Choosing the highest rate seen once can cause a stall if the next download slows down. Players also try to avoid distracting, frequent quality switches.

Calculate a segment download

Consider 4 s segments encoded at 1, 2.5, 5 and 8 Mbps. At a measured throughput of 6 Mbps, the 5 Mbps segment contains 20 Mbit. It downloads in about 3.33 s, adding 4 s of playable content while playback uses about 3.33 s. With playback continuing, the buffer grows by about 0.67 s.

An 8 Mbps segment contains 32 Mbit and takes about 5.33 s, so the buffer shrinks by about 1.33 s. The path's 6 Mbps is a transfer rate; it does not turn an 8 Mbps encoding into a 6 Mbps encoding.

If throughput falls to 3 Mbps, the same 5 Mbps segment takes about 6.67 s. The buffer loses about 2.67 s per segment. Switching to the 2.5 Mbps version produces a 10 Mbit segment that takes about 3.33 s, allowing the buffer to grow again. For uninterrupted playback during a download, the starting buffer must also last until new playable data is available.

Stored streams and interactive calls

Stored-video streaming uses ordinary HTTP objects, which browser caches and CDN servers can serve. It therefore runs over TCP or QUIC according to the HTTP version. Interactive calls often use UDP-based media transport because waiting for older media can be worse than losing it.

A live event can also use segmented HTTP streaming, but the player waits for each segment to be produced and keeps a buffer behind the live action. Shorter segments can reduce that delay while increasing the number of requests. Seeking to an unbuffered location also requires refilling the player, which can briefly lower quality.

Key Takeaways

  • Encoded bit rate measures data needed per second of playback.
  • A segment's size is its duration times its encoded rate.
  • Buffer change during continuous playback is segment duration minus download time.
  • DASH clients select versions using throughput estimates and buffer level.
  • Stored HTTP video uses TCP or QUIC; interactive calls have different timing needs.

5.3 CDN placement and request routing

A content distribution network, or CDN, serves copies of content from many locations. It avoids sending every viewer to one distant data center and reduces repeated long-distance transfers. Distributing service capacity also reduces dependence on one site.

Put content near its users

A private CDN belongs to one provider; a third-party CDN serves many customers. Both can deliver images, scripts, software and web pages as well as video. The original content source is the origin. CDN clusters hold copies so the origin does not handle every request.

There are two useful placement strategies:

StrategyPlacementTrade-off
Enter deepMany smaller clusters within access ISP networksShort paths to users, but many sites to maintain
Bring homeFewer larger clusters at internet exchange pointsSimpler management, but longer paths for some users

Placement and content filling are separate choices. With pull, a cluster missing an object fetches it from the origin or another cluster, stores it and serves it. With push, the provider sends objects in advance, often during quiet periods. A pull CDN's first request for an uncached object can still depend on the origin.

Trace a DNS handoff

A user requests https://video.stream.example.com/v/6Y7B23V:

  1. The user's resolver asks about video.stream.example.com.
  2. The provider's authoritative server returns a CNAME into the CDN's namespace, such as a1105.cdn.example.net.
  3. The resolver follows that name to the CDN's authoritative DNS service.
  4. The CDN selects a cluster and returns an address such as 198.51.100.17.
  5. The client connects to that server with HTTPS and requests the content.

The CNAME changes where name resolution continues. DNS returns naming information; the video bytes arrive through HTTP afterward. If the content is segmented, many ordinary segment requests follow the same basic path to a selected server.

Choose a useful location

The closest cluster on a map may have a poor network path or be overloaded. A DNS-based decision may see the resolver's location, which can be far from the user. Better selection can use measured delay and loss, current load, and sometimes information about the client's network.

IP anycast provides another route to nearby service: several locations advertise the same IP address, and internet routing chooses a path to one of them. The resulting location depends on routing, not simply physical distance. A server close to the viewer can still deliver poor video if the viewer's own access link is the bottleneck.

Netflix's Open Connect places appliances inside ISP networks and connects at exchange locations. Content is filled ahead of demand, reducing busy-hour upstream traffic. Its application services and encoded video delivery need not run on the same infrastructure. Other private CDN designs can fill caches on demand. In each case, adaptive streaming controls what rate the player requests, while the CDN helps determine the path and server from which those requests are served.

Key Takeaways

  • A CDN distributes copies and serving capacity across locations.
  • Enter deep and bring home trade path length against site-management cost.
  • Pull fills on demand; push fills ahead of requests.
  • A DNS CNAME can hand name resolution to a CDN.
  • Cluster selection depends on network performance and load as well as geography.
  • CDNs and adaptive streaming address different parts of video delivery.
6

Programming with UDP and TCP sockets

A socket program makes transport behavior visible: a datagram arrives as one message, while a TCP receive returns whatever bytes are ready. Build a small text service with each transport and follow how the server knows where to reply. Then add message framing to the TCP version and send a real HTTP request, connecting Python's socket calls with the protocol exchanges and failure cases behind them.

6.1 A UDP service in Python

Python sockets send bytes. Encode a string before sending and decode the received bytes afterward; the default text encoding is UTF-8. AF_INET selects IPv4 and SOCK_DGRAM selects UDP. Start with a local service so both processes can use loopback address 127.0.0.1.

Run the receiver first

This server handles short text datagrams and replies in uppercase:

from socket import socket, AF_INET, SOCK_DGRAM

with socket(AF_INET, SOCK_DGRAM) as server:
    server.bind(("127.0.0.1", 12000))
    while True:
        data, client_addr = server.recvfrom(2048)
        reply = data.decode().upper().encode()
        server.sendto(reply, client_addr)

bind gives the socket its receiving address and port. Binding to 127.0.0.1 accepts only local traffic. The empty address string "" instead binds to all IPv4 interfaces, making the service reachable from other hosts when the network permits it. Stop the running server before starting another copy on the same endpoint.

recvfrom blocks until a datagram arrives. It returns the data and sender's address, including the sender's port. The server uses that returned pair as the destination of sendto, so it can reply to clients whose ephemeral ports it did not know in advance.

Send a request and bound the wait
from socket import socket, AF_INET, SOCK_DGRAM

with socket(AF_INET, SOCK_DGRAM) as client:
    client.settimeout(2.0)
    client.sendto(b"hello network", ("127.0.0.1", 12000))
    try:
        data, server_addr = client.recvfrom(2048)
        print(data.decode())
    except TimeoutError:
        print("No reply within 2 seconds")

The b prefix creates a bytes literal; "hello network".encode() produces the same bytes. The operating system assigns the client's local port when needed. The expected response is HELLO NETWORK. Neither program calls listen or accept, because UDP has no transport connection setup.

A missing response does not tell the client exactly what failed. The request or reply may be lost, or no server may be listening. The timeout lets the application regain control. Some systems can report a closed destination port as an error; Windows may raise ConnectionResetError during receive.

Respect datagram boundaries

Each receive handles one datagram. Two datagrams are not combined into one message. If the receive buffer is too small, the excess of that datagram is discarded on typical Unix systems; Windows can report an error instead. Another receive does not recover the missing tail. Choose a buffer large enough for the application's expected messages.

The IPv4 UDP payload limit is 65,507 bytes with a minimum-size IPv4 header. That is a protocol maximum, not a useful target for routine datagram size. A program that needs loss detection can number messages, record send times with time.perf_counter(), and count timeouts. Two timeouts from ten requests give a measured loss rate of 20%. Retrying a request can cause duplicate processing, so a timeout-and-retry design may also need a way to recognize repeated message numbers.

Key Takeaways

  • SOCK_DGRAM creates a UDP socket; encode and decode connect bytes with text.
  • bind chooses the receiving endpoint; loopback restricts access to the same host.
  • recvfrom supplies the sender address needed for a reply.
  • A timeout bounds the wait but does not identify the cause of missing data.
  • A receive buffer that is too small can lose the tail of a UDP datagram.

6.2 A TCP service with complete messages

TCP gives the program an ordered byte stream. It does not preserve the boundaries of sendall calls. A complete short test can arrive in one recv, but a correct program must also handle a request split across several receives.

Frame one text request

Choose a newline delimiter. The client sends one UTF-8 line, and the server returns one uppercase line. This server reads until it finds that delimiter before decoding:

from socket import socket, AF_INET, SOCK_STREAM

with socket(AF_INET, SOCK_STREAM) as server:
    server.bind(("127.0.0.1", 12000))
    server.listen(5)
    while True:
        conn, client_addr = server.accept()
        with conn:
            data = b""
            while b"\n" not in data:
                chunk = conn.recv(1024)
                if not chunk:
                    break
                data += chunk
            if b"\n" in data:
                line = data.split(b"\n", 1)[0]
                conn.sendall(line.decode().upper().encode() + b"\n")

listen creates a listening, or welcoming, socket. accept returns a new connection socket and the client's address. Use conn for this client's bytes; the original socket remains available to accept more connections. Here, clients are served one at a time. The backlog of five concerns pending connections, not five active worker threads.

Complete the client side
from socket import create_connection

with create_connection(("127.0.0.1", 12000), timeout=2) as client:
    client.sendall(b"hello network\n")
    data = b""
    while b"\n" not in data:
        chunk = client.recv(1024)
        if not chunk:
            raise EOFError("Reply ended before its newline")
        data += chunk
    print(data.split(b"\n", 1)[0].decode())

The expected result is HELLO NETWORK. sendall keeps sending until all supplied bytes are handed off or an error occurs. A single send may send only part and reports how many bytes it accepted. Neither call supplies application message boundaries to the receiver.

This service accepts one line per connection. A persistent multi-message service would retain bytes after the first newline for its next message. Length prefixes and closing the sending direction are other framing choices. Receiving b"" means the peer has ended its sending side; it is not an empty chunk to keep retrying.

Connect the code to real protocols

An HTTP/1.1 request is also a sequence of bytes:

from socket import create_connection

request = ("GET / HTTP/1.1\r\n"
           "Host: example.com\r\n"
           "Connection: close\r\n\r\n")
with create_connection(("example.com", 80), timeout=5) as sock:
    sock.sendall(request.encode("ascii"))
    chunks = []
    while True:
        chunk = sock.recv(4096)
        if not chunk:
            break
        chunks.append(chunk)
print(b"".join(chunks).decode(errors="replace")[:200])

This displays the start of the raw response, including its status and headers. A server can return an error or redirect; the code does not assume a particular response body. HTTPS on port 443 needs TLS wrapping with certificate and host-name verification, not just a changed port number. For example, ssl.create_default_context().wrap_socket(sock, server_hostname="example.com") wraps a connected socket after import ssl. A refused connection commonly means no listener; silently dropped traffic can time out. For quick server restarts on Unix, setting SO_REUSEADDR before bind can permit reuse when an old connection is closing; it does not let two active listeners own the same endpoint. Concurrent servers use threads or event loops, and distinguish connections by both endpoint address-port pairs.

Key Takeaways

  • accept returns a connection socket distinct from the listening socket.
  • TCP messages need framing and receive loops.
  • sendall handles partial sending; recv can still return partial data.
  • An empty TCP receive signals the end of the peer's sending direction.
  • An HTTP/1.1 request needs CRLF line endings and the final blank line.
  • HTTPS requires TLS as well as port 443.
  • A backlog controls pending connections, not application concurrency.

Application Layer examples

6 Walkthroughs

1

Choose an application design and transport

9 steps
Follow a file-sharing design from host roles to the transport service its processes need.
  1. 1
    IntroductionStart with the programs

    A network service is built from programs at the ends of the network. Imagine distributing a research data set to a growing group: someone must locate the data, send it, and receive it. Follow those responsibilities to compare client-server and P2P designs, then decide what the processes need from their transport service.

  2. 2
    ExplanationPut the content on dedicated servers

    In a client-server design, clients request data from an always-on service at a known address. The service can use many machines behind one name, but the provider still supplies that serving capacity. If every researcher downloads a complete copy from the service, more researchers mean more upload work for its servers. Routers carry the packets without running the file-sharing application.

  3. 3
    ExampleLet participants contribute uploads

    In a P2P design, a researcher who has received some chunks can send them to another researcher before finishing the whole file. A joining peer adds demand, but also potential upload capacity. That is the source of self-scaling. A slow upload link, a disconnected peer or a peer unwilling to share weakens the benefit, so discovery, availability and incentives matter.

  4. 4
    ChallengeClassify the path carrying the file

    A directory lists who has a data set. Researchers then exchange its chunks directly. Is every file transfer client-server, and who is the client when one peer requests a chunk?

    ---reveal---

    The overall design is a hybrid: server-based discovery and peer data transfer. The peer initiating the chunk request is the client for that exchange; the responding peer takes the server role.

  5. 5
    ExplanationLocate one receiving endpoint

    A process uses a socket to access the transport layer. The destination needs both a host IP address and a port: the IP address reaches the host, and the port distinguishes its receiving service. For an HTTPS service at 203.0.113.10, the usual port is 443. The client can use an operating-system-assigned ephemeral source port, so the two ends need not use the same port number.

  6. 6
    ExampleChoose which delay matters

    A game sends a fresh position 30 times per second, about every 33 ms. Recovering an old update may be less useful than acting on the next one, so UDP can suit this traffic. A downloaded configuration file must be complete, so it needs reliable delivery. This choice concerns the meaning and timing of the data; choosing UDP does not itself make the path uncongested or reserve bandwidth.

  7. 7
    ConnectionAdd the services that are missing

    TCP supplies reliable, ordered bytes, flow control and congestion control, but not encryption or a deadline. TLS can secure its traffic. UDP supplies datagrams and preserves their boundaries but leaves loss and ordering to higher layers. HTTP/3 gets reliable streams and TLS 1.3 through QUIC over UDP. Identify the full stack before judging the service from its lowest visible protocol.

  8. 8
    ChallengeDesign a secure peer exchange

    Two peers need to exchange a complete private document. One initiates contact, and the transfer uses bare UDP. What are their exchange roles, and what services does this design still need?

    ---reveal---

    The initiator is the client and the responder is the server for that exchange. Bare UDP does not supply complete ordered delivery or confidentiality. The design needs reliability and security above UDP, or a transport stack that provides them.

  9. 9
    RecapTrace roles before choosing transport

    When assessing a design, first trace who sends the content and who only helps locate it. Then identify the receiving endpoint and the services the content needs: correct delivery, adequate throughput, timely arrival and protection. Those decisions explain both the application architecture and why a transport stack is suitable. A socket connects the process to that chosen service.

2

Read and improve an HTTP exchange

15 steps
Work from HTTP/1.1 messages and timing through cache validation and QUIC streams.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow a page load
  2. 2
    ExampleRead the request structure
  3. 3
    ExplanationSeparate setup from transmission
  4. 4
    ExampleFinish the timing calculation
  5. 5
    ChallengeCount the dependency stages
  6. 6
    ExplanationRecognize a returning browser
  7. 7
    ExampleChoose the hit or miss path
  8. 8
    ExplanationValidate without another object body
  9. 9
    ChallengePredict the second request
  10. 10
    ExplanationInterleave response frames
  11. 11
    Key InsightLocate blocking below HTTP
  12. 12
    ExampleCompare fresh secure setup
  13. 13
    TipKeep meaning separate from transport
  14. 14
    ChallengeDiagnose a cached HTTP/3 request
  15. 15
    RecapIdentify which cost is removed
3

Trace and read a DNS lookup

11 steps
Follow resolver queries, cached referrals and the resource records inside a response.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFind a service before contacting it
  2. 2
    ExplanationStart at the local resolver
  3. 3
    ExampleFollow each referral
  4. 4
    ExampleAdd the waiting intervals
  5. 5
    ChallengePredict an address update
  6. 6
    ExplanationChoose the right record question
  7. 7
    ExampleRead the reply sections
  8. 8
    ConnectionKeep protection goals separate
  9. 9
    ChallengeInterpret a mail referral
  10. 10
    ChallengeCombine caching with the right record
  11. 11
    RecapCheck what each name identifies
4

Follow an email from submission to reading

11 steps
Connect SMTP envelopes, MIME content and mailbox access in one delivery story.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate transfer from reading
  2. 2
    ExplanationHand work to an outgoing server
  3. 3
    ExampleGive SMTP its envelope
  4. 4
    Key InsightDistinguish the displayed addresses
  5. 5
    ChallengeExplain the hidden recipient
  6. 6
    ConnectionAuthenticate the right domain
  7. 7
    ExplanationRepresent an attachment
  8. 8
    ExampleKeep mailbox state on the server
  9. 9
    ChallengeChoose access for two devices
  10. 10
    ChallengeTrace a webmail message end to end
  11. 11
    RecapAssign each symptom to its stage
5

Reason about file and video delivery

16 steps
Work through distribution bounds, buffer arithmetic and CDN request routing.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFind the limiting resource
  2. 2
    ExplanationCount the copies a server uploads
  3. 3
    ExplanationAdd peer contributions
  4. 4
    ExampleCalculate the available capacity
  5. 5
    ExampleCompare all simultaneous limits
  6. 6
    ChallengeRemove the right bottleneck
  7. 7
    ConnectionChoose chunks and upload partners
  8. 8
    ExplanationMeasure playable seconds
  9. 9
    ExampleTurn one segment into bits
  10. 10
    ExampleRespond when throughput falls
  11. 11
    ChallengeCheck the buffer before arrival
  12. 12
    ExplanationPlace copies along shorter paths
  13. 13
    ExampleHand name resolution to a CDN
  14. 14
    ChallengeChoose by performance, not only a map
  15. 15
    ChallengeCombine a CDN hit with adaptation
  16. 16
    RecapMatch improvements to their constraints
6

Build and debug a socket exchange

14 steps
Follow UDP datagrams, frame TCP messages and connect the socket API to HTTP.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake transport behavior visible
  2. 2
    ExampleCreate and bind a UDP socket
  3. 3
    ExampleReceive a datagram and return it
  4. 4
    TipBound the wait for a reply
  5. 5
    ChallengePredict a too-small receive
  6. 6
    ExplanationAccept a TCP connection
  7. 7
    ExampleObserve a split message
  8. 8
    ExampleAccumulate bytes through the delimiter
  9. 9
    ChallengeKeep bytes belonging to the next message
  10. 10
    TipSend every response byte
  11. 11
    ConnectionWrite an HTTP request as bytes
  12. 12
    ExplanationSeparate waiting connections from workers
  13. 13
    ChallengeDiagnose two waiting programs
  14. 14
    RecapCheck endpoints, bytes and completion

Application Layer practice questions

50 Practice Questions in 5 sets

Set 1: DNS records and the email journey10 Practice Questions

Question 1 of 10

What does an authoritative DNS server provide for a domain it serves?
  1. Recursive resolution of names for hosts.
  2. The domain's published resource records.
  3. The web objects named by the domain's URLs.
  4. A source port for each browser connection.
Show answerHide answer
Answer: B
An authoritative server publishes the records for the names it serves. A local recursive resolver gathers answers for hosts and may consult that server. Publishing the records does not make the authoritative server the machine that serves the domain's web objects.

Question 2 of 10

A DNS reply contains assets.example.net CNAME edge.cdn.example.org. The resolver has no address for the target. What information must it obtain before the client can connect over IPv4?
  1. An MX record for assets.example.net.
  2. An NS record whose value is the CDN server IP address.
  3. A PTR record whose value is the HTTP object path.
  4. An A record for edge.cdn.example.org.
Show answerHide answer
Answer: D
The CNAME supplies another host name, so IPv4 connection setup still requires its A record. An MX record selects a mail server and does not resolve this web alias. An NS record also contains a name, not the server IP address suggested by that mistaken interpretation.

Question 3 of 10

A domain has MX entries with preferences 15 and 35. Which server should a sender normally try first?
  1. The server with preference 15.
  2. The server with preference 35.
  3. The server named in the web host's CNAME.
  4. The server with the longer DNS TTL.
Show answerHide answer
Answer: A
For MX records, the lower preference value is preferred, so the sender tries 15 first. A higher value is often mistaken for higher priority. TTL instead controls how long the record may be cached; it does not rank the domain's mail destinations.

Question 4 of 10

A resolver caches an address with TTL 900 s. The authoritative address changes 240 s later. How much longer may the resolver keep using the old cached answer?
  1. 240 s.
  2. 900 s.
  3. 660 s.
  4. 1,140 s.
Show answerHide answer
Answer: C
The cached record has used 240 s of its 900 s lifetime, leaving 660 s. The authoritative update does not restart or instantly erase that cached lifetime. Returning 900 s would treat the later address change as if it created a new copy of the old record.

Question 5 of 10

A UDP DNS response arrives with the TC flag set and lacks the full answer. How should a resolver obtain the complete response in the usual fallback?
  1. Retry the query over TCP port 53.
  2. Retry the query over UDP port 80.
  3. Treat the missing records as NXDOMAIN.
  4. Open a TCP connection on port 25.
Show answerHide answer
Answer: A
The TC flag marks truncation, so the resolver can retry the query using TCP on DNS port 53. Missing data in a truncated reply does not mean the name is nonexistent. NXDOMAIN is a distinct DNS error response, not an inference from an incomplete answer.

Question 6 of 10

What should a sending mail server normally do after a temporary 4xx SMTP rejection?
  1. Mark it delivered and drop the queue entry.
  2. Keep the message queued for a later retry.
  3. Treat the mailbox as permanently nonexistent.
  4. Switch the delivery from SMTP to IMAP.
Show answerHide answer
Answer: B
An SMTP 4xx reply reports a temporary failure, so the sending server retains the message for retry. A permanent 5xx rejection has different handling and often leads to a delivery failure report. IMAP accesses stored mail and cannot replace the rejected SMTP transfer.

Question 7 of 10

A message is accepted for RCPT TO:<archive@example.net>, but its visible To: field names team@example.net. Which address controls this accepted delivery?
  1. team@example.net in the visible message header.
  2. The sender address appearing in MAIL FROM.
  3. The host name supplied by the EHLO command.
  4. archive@example.net in the SMTP envelope.
Show answerHide answer
Answer: D
RCPT TO identifies an envelope recipient and controls the delivery described here. The visible To field is part of the message and can name a different address. MAIL FROM supplies the envelope sender for purposes such as delivery-failure reporting; it is not the recipient.

Question 8 of 10

A phone should see folders and read flags changed on a laptop. Which access method directly supports that server-side mailbox state?
  1. POP3 download-and-delete per device.
  2. SMTP transfer between the devices.
  3. IMAP access to the shared mailbox.
  4. POP3 download-and-keep on both devices.
Show answerHide answer
Answer: C
IMAP stores mailbox folders and flags on the server, so both devices can observe the same state. POP3 download-and-keep leaves message copies available, but it does not synchronize server folders or read flags. Keeping messages is different from sharing their organization.

Question 9 of 10

A message displays From: help@example.org, uses an envelope sender at mailer.example.net, passes SPF for example.net, and has no valid DKIM signature. Why does the SPF success not produce a DMARC pass for the displayed domain?
  1. The passing SPF check must use the recipient's domain instead.
  2. The passing SPF domain is not aligned with the From domain.
  3. The passing SPF result needs an MX preference lower than 10.
  4. The passing SPF result is valid only when SMTP uses port 465.
Show answerHide answer
Answer: B
SPF authenticates the envelope domain, here example.net, while DMARC ties authentication to the visible From domain. These domains are unrelated, and no aligned DKIM pass is available, so the SPF pass is insufficient. Merely authenticating some domain does not authenticate the displayed sender.

Question 10 of 10

A server permits messages of at most 8 MB. A sender attaches two 3 MB binary files encoded in base64. What follows about whether the complete message can fit?
  1. It exceeds the limit once message overhead is included.
  2. It fits with 2 MB available for headers and text.
  3. It fits exactly because all message overhead is already included.
  4. It exceeds the limit only if the two files have different types.
Show answerHide answer
Answer: A
The attachments total 6 MB before encoding, becoming 8 million base64 characters before line breaks. Message headers, separators and other content then push the message above 8 MB. Comparing only the raw 6 MB with the limit ignores the encoding overhead that fills the available space.
Set 2: Processes, HTTP and lookup decisions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A cache has a 30% hit rate. Hits take 8 ms and misses take 180 ms. What is the mean response time?
  1. 59.6 ms.
  2. 128.4 ms.
  3. 94 ms.
  4. 172 ms.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A file-sharing peer initiates a chunk request to another peer. What role does the requesting process have in this exchange?
  1. The server role.
  2. The tracker role.
  3. The client role.
  4. The relay role.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A service uses one host to list available participants, but participants send file chunks directly to each other. How is this service organized?
  1. A hybrid with centralized discovery and peer data transfer.
  2. A client-server service with centralized file delivery.
  3. A pure P2P service without any dedicated coordination host.
  4. A caching proxy service with origin-based participant discovery.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A host runs several network services. What destination information lets a sender reach the intended receiving endpoint?
  1. The host IP address and file path.
  2. The service port and object content type.
  3. The host name and response status code.
  4. The host IP address and service port.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A sensor app sends independent updates that quickly become stale, but its configuration downloads must arrive completely. What transport design fits these two needs?
  1. TCP for updates and unprotected UDP for configuration.
  2. UDP for updates and a reliable service for configuration.
  3. Unprotected UDP for both, since it preserves message boundaries.
  4. TCP for both, since it guarantees each update a deadline.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An HTTP server returns 404 Not Found for /handbook.pdf. What has this exchange established?
  1. The server never accepted the transport connection.
  2. The request succeeded, but the browser rejected the file.
  3. The server answered, but that resource was not found.
  4. The server redirected the resource to a new address.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A new plain HTTP TCP connection has RTT 25 ms. A 300 kB object crosses a 40 Mbps path. What is its approximate fetch time, ignoring DNS and processing?
  1. 60 ms.
  2. 85 ms.
  3. 160 ms.
  4. 110 ms.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What does Cache-Control: no-cache require before a stored response is reused?
  1. Validate it with the origin.
  2. Refuse to store it at all.
  3. Reuse it until the browser exits.
  4. Keep it only in a shared proxy.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A resolver has a valid cached delegation to a domain's authoritative servers but no cached address for the requested host. Where can it send its next lookup?
  1. To a root server to restart the lookup.
  2. To the requested web server directly.
  3. To one of those authoritative servers.
  4. To the browser cache for the delegation.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A page has one tiny HTML object and six tiny images. RTT is 15 ms. Compare sequential non-persistent plain HTTP with non-persistent fetching using three parallel image connections per batch after HTML. Ignore transmission, DNS and processing. How much time does batching save?
  1. 120 ms.
  2. 90 ms.
  3. 150 ms.
  4. 165 ms.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Content delivery and socket behavior10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A BitTorrent peer needs several chunks. Which chunk does rarest-first selection favor?
  1. The needed chunk held by the fewest neighbors.
  2. The needed chunk from the fastest neighbor.
  3. The needed chunk that comes earliest in the file.
  4. The needed chunk most requested by other peers.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What information does a DASH manifest give the player for choosing and requesting segments?
  1. Current path throughput, buffer level and next chosen rate.
  2. Available encoded versions, bit rates and segment URLs.
  3. One fixed encoding and a single full-video download URL.
  4. Available server locations without encoded version information.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A server uploads at 60 Mbps to 12 clients, each downloading at 15 Mbps. What is the client-server distribution-time lower bound for a 900 Mbit file?
  1. 15 s.
  2. 60 s.
  3. 240 s.
  4. 180 s.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A 5 s video segment is encoded at 3 Mbps and downloaded at 6 Mbps during continuous playback. How does the buffer change after the complete segment arrives without a stall?
  1. It shrinks by 2.5 s.
  2. It grows by 2.5 s.
  3. It grows by 5 s.
  4. It remains unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A CDN server has no copy of a requested image, fetches it from the origin, then retains it for later requests. What placement behavior is this?
  1. Pull filling on a cache miss.
  2. Push filling before requests.
  3. Origin relay with no local copy.
  4. Peer delivery from other viewers.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A UDP server receives data from (192.0.2.44, 53018). Where should it send the reply for that request?
  1. To 192.0.2.44 on the server port.
  2. To its own IP on port 53018.
  3. To 192.0.2.44 on port 53018.
  4. To 192.0.2.44 on an unused port.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A TCP server receives b"part" from the first recv(1024) of a newline-delimited request. What must it do before treating that request as complete?
  1. Treat the four bytes as the full request now.
  2. Keep receiving until the newline or end of stream.
  3. Call accept again to get the rest of the request.
  4. Increase the listen backlog to get the remaining bytes.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

For a 1,200 Mbit file, 30 peers each upload at 2 Mbps and the slowest downloads at 12 Mbps. The server uploads at 60 Mbps. How much does P2P reduce the lower bound compared with client-server, assuming only access-link bottlenecks?
  1. 100 s.
  2. 500 s.
  3. 580 s.
  4. 300 s.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A player has 3 s buffered and requests complete 4 s segments at either 2 or 4 Mbps. Throughput stays at 3 Mbps; only complete segments become playable. Which choice avoids a stall on the next download and increases the buffer?
  1. The 4 Mbps version.
  2. Either version, since both segments last 4 s.
  3. The 2 Mbps version.
  4. Neither version, since the buffer is shorter than a segment.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A viewer's public DNS resolver is far away. CDN cluster A is nearest that resolver but has a congested path to the viewer; cluster B has a faster measured path to the viewer. What selection change addresses this problem?
  1. Choose only by physical distance from the public resolver.
  2. Increase DNS TTL so the resolver keeps cluster A longer.
  3. Use a higher encoded rate whenever the resolver is distant.
  4. Use client-network performance evidence when selecting the cluster.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Trace failures and repair protocol reasoning10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does Python's accept() return to a listening TCP server?
  1. The complete next request and its byte length.
  2. The original listener and a new server port number.
  3. A UDP datagram and the sender's message number.
  4. A new connection socket and the client address.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A request includes If-None-Match: "r9", and the origin returns 304 Not Modified. How should a cache satisfy the request?
  1. Replace the stored representation with the empty response body.
  2. Reuse the stored representation validated by that response.
  3. Repeat an unconditional GET because every 304 is a failure.
  4. Delete the stored representation because its ETag is invalid.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Several HTTP/2 streams share one connection. A lost TCP segment prevents later bytes from being delivered. Why can a response whose own bytes arrived also wait?
  1. TCP delivers the connection's bytes in one overall order.
  2. HTTP/2 requires every response body to finish in request order.
  3. Each HTTP/2 stream opens a new TCP connection after any loss.
  4. HPACK requires every lost body frame to be compressed again.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

On a Unix host, a UDP receiver uses a 500-byte buffer for an arriving 700-byte datagram. What happens to the unread tail?
  1. The 200-byte tail is read next.
  2. The datagram stays queued intact.
  3. The 200-byte tail is discarded.
  4. The sender resends the 200 bytes.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A user sends a message through webmail to a different provider. What protocol combination describes the browser connection and the usual server-to-server transfer?
  1. SMTP at the browser; HTTPS between mail servers.
  2. IMAP at the browser; POP3 between mail servers.
  3. HTTPS at the browser; IMAP between mail servers.
  4. HTTPS at the browser; SMTP between mail servers.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A torrent has many peers downloading but contributing almost no upload capacity. Why is adding these peers unlikely to give the usual self-scaling benefit?
  1. Their download links remove the need for server upload.
  2. Their presence changes every existing chunk into a full file.
  3. They add demand without much usable distribution capacity.
  4. Their tracker queries count as equivalent file upload capacity.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A cold DNS lookup has host-resolver RTT 4 ms, root RTT 12 ms, TLD RTT 18 ms and authoritative RTT 26 ms. A later lookup uses cached root and TLD referrals but has no final answer cached. How much faster is the later lookup, ignoring processing?
  1. 30 ms faster.
  2. 26 ms faster.
  3. 34 ms faster.
  4. 56 ms faster.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A persistent newline protocol receives b"red\nblu", then b"e\n". What request handling preserves both messages correctly?
  1. Process red, discard blu, then process e as the second request.
  2. Process red, retain blu, then combine it with e and process blue.
  3. Wait for closure and process red plus blue as one request.
  4. Process red and blu immediately, then process e separately.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A tiny page has one HTML object and four images. RTT is 20 ms. Compare one persistent HTTPS connection with sequential requests against sequential fresh HTTPS connections for all objects. Each fresh connection uses one TCP and one TLS 1.3 setup RTT. Ignore other costs. What time does reuse save?
  1. 160 ms.
  2. 80 ms.
  3. 120 ms.
  4. 200 ms.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A player starts with 7 s buffered. It downloads three complete 3 s segments encoded at 4 Mbps over a steady 3 Mbps path, with continuous playback and no overlap between downloads. What buffer remains, and does a stall occur during these downloads?
  1. 4 s remains, with a stall in the last download.
  2. 4 s remains, with no stall.
  3. 7 s remains, with no stall.
  4. 10 s remains, with no stall.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Bottlenecks, dependencies and design choices10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Which transport provides the reliable streams used by HTTP/3?
  1. TLS over bare UDP.
  2. QUIC over UDP.
  3. TCP over QUIC.
  4. HTTP/2 over TCP.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An app switches a file transfer from TCP to bare UDP but still requires every byte in order. What functionality must its design now provide above UDP?
  1. Only a destination port, since UDP guarantees ordering.
  2. Only message lengths, since UDP already orders arrivals.
  3. Loss recovery and ordering of the transferred data.
  4. Only encryption, since UDP already recovers missing data.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A viewer plays a 6 Mbps video from a CDN cache. The viewer’s access link can carry 4 Mbps, while the cluster has spare capacity. Why might moving the cached copy to an even closer CDN site fail to remove stalls?
  1. The viewer’s access link can remain the limiting bottleneck.
  2. The origin must approve every segment before a cache can serve it.
  3. The chosen video encoding fixes the capacity of the access link.
  4. A cache hit avoids origin work but always increases video bit rate.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A UDP client times out after sending a request. Why can it not conclude that the server program was stopped?
  1. A timeout confirms the server rejected the syntax.
  2. Timeouts occur only when no process has bound the port.
  3. A timeout confirms the server changed its address.
  4. Either the request or reply could have been lost.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An access link is 50 Mbps. Requests arrive at 50 per second, each for a 1 Mbit object. Cache hits take 4 ms and misses 100 ms. What minimum hit rate makes mean response time at most 40 ms, and what link intensity then remains? Assume the two path delays stay fixed.
  1. 60% hits and intensity 0.4.
  2. 37.5% hits and intensity 0.625.
  3. 62.5% hits and intensity 0.625.
  4. 62.5% hits and intensity 0.375.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A 600 Mbit file goes to 20 peers, each uploading at 5 Mbps. Server upload is 100 Mbps. The slowest peer downloads at 2 Mbps; all other downloads are faster. Would doubling server upload reduce the P2P lower bound, assuming only access-link bottlenecks?
  1. No; the 300 s slowest-download term remains dominant.
  2. Yes; the bound falls from 120 s to 60 s.
  3. Yes; the bound falls from 300 s to 150 s.
  4. No; the 120 s server-copy term remains dominant.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A resolver receives example.org NS ns.example.org and an additional A record locating that name server, but no A record for lab.example.org. What must it do to locate the lab host, and why?
  1. Connect to the added address as the lab host; additional A records answer all subdomains.
  2. Ask the named server for the lab NS record; its value supplies the requested host address.
  3. Ask the named server for the lab A record; the added address locates the DNS server.
  4. Return NXDOMAIN for the lab host; a referral without its A record proves absence.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A message is submitted to a server, then the sender closes the laptop. The recipient domain has MX preferences 12 and 28. Server 12 returns a temporary failure; server 28 cannot be reached. The recipient uses IMAP. What should happen next, and where should the recipient expect the message now?
  1. Delete it as a permanent failure; IMAP can recover it from the sender’s laptop.
  2. Keep it queued at the sending server; it is not yet in the recipient mailbox.
  3. Mark it delivered through server 12; a temporary response puts it in IMAP storage.
  4. Move it into the sender’s IMAP mailbox; that mailbox now handles delivery retries.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A phone switches from Wi-Fi to cellular, changing its IP address while downloading two HTTP/3 objects. A packet carrying bytes only for stream X is lost; Y’s complete data arrives with no application dependency on X. What can happen to the connection and the two streams?
  1. The connection can remain; X waits for recovery while Y’s received data can be delivered.
  2. The connection can remain; both streams must wait for the missing X bytes to be recovered.
  3. The connection must restart; both objects must be requested again despite received Y data.
  4. The connection can remain; Y proceeds only if X abandons reliable ordered delivery.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A TCP client sends one newline-delimited request with sendall, then waits for a reply while keeping its connection open. The server waits for EOF before replying. Why can both programs wait indefinitely, and what compatible change fixes it?
  1. The client used sendall; replacing it with one send guarantees completion.
  2. The server backlog is full; increasing it makes this request reach EOF.
  3. The server waits for closure; it should recognize the request's newline.
  4. TCP lost the message boundary; a larger recv guarantees the sender's call boundary.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

88 Key Terms, each with its definition

A

A record
An A record associates a DNS host name with an IPv4 address, allowing a client to locate that host on an IPv4 network.
An A record for www.example.org can return the documentation address 203.0.113.25 in a worked lookup.
AAAA record
An AAAA record associates a DNS host name with an IPv6 address, providing an IPv6 alternative to IPv4 address records.
An AAAA record can return 2001:db8::25 for a host in an illustrative IPv6 lookup.
Application-layer protocol
An application-layer protocol defines message types, field syntax, meaning and the rules for exchanges between processes.
HTTP is an application-layer protocol that lets separately written browsers and servers exchange objects.
Authoritative server
An authoritative server publishes DNS records for the names within the zones it serves, supplying answers from that authority.
The authoritative server for a domain returns the published address record for its web host.

B

Backlog
A backlog is the queue allowance for pending connection requests waiting to be accepted by a listening server socket.
Increasing the backlog does not make a server’s one-at-a-time request handler run concurrently.
Base64
Base64 encodes groups of three bytes as four ASCII characters, adding about one third to data size before message overhead.
A 3 MB attachment becomes 4 million base64 characters before the line breaks and headers are added.
Bind
Bind is the socket operation that assigns a local address and port to an endpoint, determining where it receives traffic.
A UDP server that calls bind with 127.0.0.1 and port 12000 receives local requests at that address and port.
Bit rate
A bit rate is data per unit time; for encoded video, it measures how many bits are needed for each second of playback.
A video bit rate of 5 Mbps produces 20 Mbit of encoded data for a constant-rate four-second segment.
Bring home
Bring home is a CDN placement strategy using fewer, larger clusters at exchange points where many networks interconnect.
Bring home simplifies management compared with maintaining many small clusters inside access networks.

C

Cache hit
A cache hit occurs when a requested response is present and usable in a cache, avoiding the ordinary origin-fetch path.
The institution sees a cache hit for a popular image already stored in its caching proxy.
Cache poisoning
Cache poisoning is insertion of false data into a resolver’s cache, causing later requests to reuse the attacker’s forged information.
A forged address accepted during cache poisoning can direct later visitors to an attacker’s host.
Cache-Control
Cache-Control is an HTTP field carrying caching directives that govern storage, freshness and validation of a response.
Cache-Control with no-store stops storage; no-cache instead requires checking before reuse.
Caching proxy
A caching proxy is an intermediary that forwards requests to origins and can satisfy eligible requests from stored responses.
The caching proxy serves a local hit but acts as a client when it fetches a missing object from the origin.
CDN
A CDN distributes serving capacity and content copies across locations to deliver objects efficiently and reduce origin load.
A CDN cluster near the viewer serves popular video segments without sending every request to the origin.
Client-server architecture
A client-server architecture assigns requests to clients and serving work to dedicated, reachable server hosts.
In a client-server architecture, a researcher downloads a data set from the publisher’s server.
CNAME record
A CNAME record makes an owner name an alias of a canonical target name, letting resolution continue through that target.
A CNAME record points media.example.org into a CDN namespace before the resolver obtains an address.
Conditional GET
A conditional GET requests a representation subject to a condition, often validating a cached date or ETag before body transfer.
A conditional GET receives 304 when the saved ETag still identifies the current representation.
Connection socket
A connection socket is a transport endpoint for one established TCP connection, used to send and receive that connection’s bytes.
The server calls recv on the connection socket returned by accept, not on the listening socket.
Cookie
A cookie is a value stored by a browser and returned with matching requests, allowing a site to recognize state across requests.
The shopping site looks up a stored cart when the browser returns its session cookie.

D

DASH
DASH is adaptive streaming over HTTP in which a client selects successive video segments from versions with different encoded rates.
DASH lets a player switch to a lower-rate version after throughput falls and its buffer begins shrinking.
Datagram
A datagram is an independently addressed message carried by a connectionless transport, with its boundary preserved on receive.
Two UDP datagrams sent separately remain separate messages even if they arrive close together.
Distribution time
The distribution time is the elapsed time needed to deliver one complete copy of a file to every intended recipient.
A fast first download does not establish distribution time if the slowest peer is still receiving its copy.
DKIM
DKIM authenticates signed message data using a domain’s digital signature and a verification key published through DNS.
A receiver checks a DKIM signature using the public key for the message’s signing domain.
DMARC
DMARC connects a successful SPF or DKIM result with the visible From domain through alignment and publishes failure policy.
A DMARC check cannot rely on an SPF pass for an unrelated domain when no aligned DKIM result passes.
DNS
DNS is a distributed naming database and an application protocol for querying records such as host addresses and mail destinations.
Before contacting a web host, the browser asks DNS for address information associated with its name.
DNSSEC
DNSSEC adds digital signatures to DNS data so validating resolvers can check authenticity and integrity of signed records.
DNSSEC helps a resolver detect forged signed data, while encrypted DNS addresses query privacy.

E

Elastic application
An elastic application can use the throughput currently available without needing one fixed minimum rate for its basic operation.
An email attachment download is an elastic application even though the user would prefer it to finish quickly.
End system
An end system is a host at the network edge that runs application processes, such as a phone, laptop or server.
A browser and web server run on end systems while routers forward the packets between them.
Enter deep
Enter deep is a CDN placement strategy using many smaller clusters inside access ISP networks to shorten paths to users.
Enter deep brings content close to subscribers but leaves the operator with many locations to maintain.
Envelope
An envelope is SMTP’s delivery information, including the MAIL FROM sender and RCPT TO recipients, separate from message headers.
A hidden recipient appears in the envelope even when no visible To header names that recipient.
ETag
An ETag is an identifier assigned to a resource representation and used in conditions that compare a saved version with the current one.
The cache sends its saved ETag in If-None-Match before deciding whether to replace the stored body.

F

Frame
A frame is a structured unit used to carry part of a message or control information within HTTP/2 or HTTP/3.
The sender schedules a data frame from a short response between frames belonging to a large response.

H

Head-of-line blocking
Head-of-line blocking is waiting caused when earlier work or missing data prevents later ready data from making progress.
A lost TCP segment creates head-of-line blocking for later bytes from several HTTP/2 streams.
HTTP method
An HTTP method states the operation requested for a resource, such as retrieval with GET or header retrieval with HEAD.
The browser uses the HTTP method GET when it retrieves a linked document from the site.
HTTP object
An HTTP object is an individually addressable resource representation, such as an HTML document, image or script, retrieved through HTTP.
The base HTML names several images, so the browser requests more than one HTTP object for the page.
HTTP/2
HTTP/2 carries HTTP messages as interleaved binary frames from multiple streams over one TCP connection and compresses headers.
HTTP/2 can finish a small image while frames of a much larger response are still being sent.
HTTP/3
HTTP/3 maps shared HTTP message meanings onto QUIC streams and binary frames, using QUIC’s integrated transport security.
HTTP/3 serves the same resource URL while changing the transport from TCP-based HTTP versions.
HttpOnly
HttpOnly is a cookie attribute that prevents page scripts from reading the cookie while allowing eligible HTTP transmission.
A login cookie marked HttpOnly can still accompany a matching request even though script cannot read it.
Hybrid architecture
A hybrid architecture combines dedicated server functions with direct peer communication within the same application.
A tracker-based file-sharing service has a hybrid architecture when peers transfer the file themselves.

I

IMAP
IMAP is a mail access protocol that keeps messages, folders and flags on the server and allows clients to retrieve selected content.
IMAP lets a phone see the read flag and folder change previously made from a laptop.
IP anycast
IP anycast advertises the same IP address from multiple locations, allowing network routing to select a path to one of them.
IP anycast can route a client toward a CDN location without assigning that location a unique client-facing address.

L

Listening socket
A listening socket waits for incoming TCP connection requests and accepts them into separate sockets for data exchange.
The listening socket stays open while the accepted connection socket carries one client’s request.
Loopback address
A loopback address routes traffic within the same host, allowing local processes to communicate without contacting another machine.
A server bound to loopback address 127.0.0.1 can be tested by a client running on the same computer.
Lower bound
A lower bound is a limit below which completion cannot occur under a model’s constraints, even with ideal scheduling.
The slowest peer’s download imposes a lower bound that extra upload capacity elsewhere cannot remove.

M

Mail queue
A mail queue stores messages awaiting transfer so a server can retry delivery after temporary destination or network failures.
The outgoing mail queue retains a message while the destination server is temporarily unavailable.
Manifest
A manifest describes the available versions and segment locations used by an adaptive player to request video content.
The player reads the manifest before selecting the next segment URL and its encoded version.
Message framing
Message framing defines how a receiver recognizes complete application messages within a byte stream, using lengths or delimiters.
Newline-based message framing lets the receiver accumulate several TCP reads until one complete line arrives.
MIME
MIME extends email format with content types, multipart structure and transfer encodings that support richer text and attachments.
MIME lets one message contain a plain-text note and a separate image attachment with its own type.
MX record
An MX record identifies a domain’s mail destination by server name and preference, with lower preference values tried first.
The MX record with preference 10 is normally tried before the same domain’s entry with preference 20.

N

NS record
An NS record names an authoritative DNS server for a domain or zone; its value is a host name, not that server’s IP address.
The NS record points to ns1.example.org, and supporting address data lets the resolver contact it.

O

Optimistic unchoke
An optimistic unchoke gives an interested peer upload service without requiring a strong current contribution, enabling exploration.
An optimistic unchoke lets a newcomer obtain initial chunks before becoming a useful trading partner.
Origin server
An origin server is the source server responsible for a representation, from which intermediaries can obtain content copies.
A pull CDN fetches an uncached image from the origin server before retaining a local copy.

P

Partial send
A partial send occurs when one send call accepts fewer bytes than supplied, requiring the remaining bytes to be sent later.
Using sendall avoids leaving a partial send unfinished when the program transmits a response buffer.
Peer-to-peer architecture
A peer-to-peer architecture lets participating hosts exchange data directly and contribute both requests and serving capacity.
A peer-to-peer architecture lets a new downloader receive chunks from several other participants.
Persistent connection
A persistent connection remains available for later requests after a response, saving repeated transport setup work.
A persistent connection carries an HTML response and later image responses without new TCP handshakes.
Playback buffer
A playback buffer holds received content awaiting display, providing a reserve of playable time during slower downloads.
A playback buffer with several seconds left can absorb a brief throughput dip without an immediate stall.
POP3
POP3 is a mail access protocol for downloading stored messages, with optional deletion from the server after a completed session.
POP3 download-and-delete on a laptop can leave a phone unable to retrieve the same message later.
Port number
A port number is a 16-bit value used with an IP address to identify a receiving transport endpoint on a host.
The client contacts the same host on port number 443 for HTTPS and 25 for mail-server transfer.
Process
A process is a running instance of a program; networked processes exchange application messages through transport endpoints.
A mail-server process can send one message while another process on the host handles web requests.
Pull placement
Pull placement fills a CDN cache in response to a request for content that the local cluster does not already hold.
Pull placement makes the first request for an uncached object depend on an upstream fetch.

Q

QUIC
QUIC is a secure transport over UDP that supplies reliable streams, congestion control, low-latency setup and connection migration.
QUIC can deliver received data on one stream while a separate stream recovers missing bytes.

R

Rarest first
Rarest first is a chunk-selection rule that requests needed chunks held by the fewest neighbors, helping preserve availability.
Rarest first chooses a scarce needed chunk before another needed chunk already available from many neighbors.
Rebuffering
Rebuffering is a playback interruption caused when playable data runs out and the player must wait for more content.
The player lowers its requested rate after rebuffering to reduce the chance of another visible pause.
Resolver
A resolver obtains DNS information for a requester, consulting caches and other servers when necessary to complete a lookup.
The campus resolver follows referrals while the laptop waits for its recursive lookup result.
Resource record
A resource record is a typed DNS entry connecting an owner name with data and a caching lifetime for that information.
One resource record maps the web host to IPv4, while another names the domain’s mail server.
Root server
A root server serves the top of the DNS hierarchy and normally refers resolvers toward the appropriate top-level domain servers.
The resolver asks a root server where it can continue a cold lookup for an org domain.
Round-trip time
The round-trip time is the interval for a small packet to travel to a destination and for a response to return.
A 30 ms round-trip time contributes twice to the first plain HTTP object fetched over a new TCP connection.

S

Seeder
A seeder is a BitTorrent peer that has the complete content and remains available to upload it to other participants.
A seeder stays online after finishing the download so new peers can obtain all needed chunks.
Segment
A segment is a short, separately requestable interval of encoded video, with versions available at different quality levels.
A segment representing four seconds of playback can take more than four seconds to download on a slow path.
Self-scaling
Self-scaling is growth in service capacity alongside demand because joining users contribute resources such as upload bandwidth.
P2P file sharing gains self-scaling when new downloaders also upload chunks they have received.
SMTP
SMTP is the application protocol used to submit and transfer email through command-reply exchanges over TCP connections.
SMTP pushes a queued message from the sender’s mail server to the recipient domain’s server.
Socket
A socket is the software interface through which an application process accesses transport services to send or receive data.
A networked game writes position updates through a socket and reads incoming updates through its socket API.
SPF
SPF lets a domain publish which hosts may send mail for it, checking the sending host against an SMTP envelope identity.
SPF can pass for an attacker-controlled envelope domain without validating a different visible From domain.
STARTTLS
STARTTLS is a protocol command that upgrades an existing unencrypted connection to TLS before later protected exchanges.
Authenticated SMTP submission on port 587 commonly uses STARTTLS before transmitting protected content.
Statelessness
Statelessness means an HTTP request can be understood independently, without the protocol requiring memory of earlier client requests.
HTTP statelessness still allows a shopping site to look up cart data using a cookie in each request.
Status code
A status code is a three-digit response value that reports the outcome of an HTTP request, such as success, redirection or error.
The status code 404 shows that an HTTP server replied but did not find the requested resource.
Stream
A stream is a logical sequence of data within a connection; HTTP multiplexing uses streams to distinguish simultaneous exchanges.
A stream carrying one page image can progress alongside another carrying a style sheet.

T

TCP
TCP is a connection-oriented transport that supplies reliable, ordered bytes with flow control and congestion control.
A TCP connection delivers the complete file in order, while the application identifies its message boundaries.
Timeout
A timeout is a limit on how long an operation waits before returning control with a failure to complete within that interval.
A receive timeout lets the UDP client report a missing reply instead of blocking indefinitely.
TLD server
A TLD server serves a top-level domain and supplies delegations identifying authoritative servers for domains beneath it.
A TLD server for org returns the delegation needed to continue toward the example.org records.
TLS
TLS is a security protocol that adds confidentiality, integrity and peer authentication to an application’s transport exchange.
A browser uses TLS over TCP to protect an HTTPS exchange with an HTTP/2 server.
Torrent
A torrent is the group of peers participating in distribution of a particular file or content set through BitTorrent.
Peers join a torrent and exchange chunks with neighbors they discover through a tracker or distributed lookup.
TTL
A TTL is the time-to-live value in a DNS record that limits how many seconds a cached copy remains reusable.
An address change can leave an old cached answer usable until the remaining TTL reaches zero.

U

UDP
UDP is a connectionless transport that carries separate datagrams without providing loss recovery, ordering or congestion control.
A small DNS query can use UDP, with a resolver retrying when no answer arrives before its timeout.
UTF-8
UTF-8 is a byte encoding for Unicode text, used by Python’s default string encode and bytes decode operations.
A server that changes received text to uppercase first decodes the incoming UTF-8 bytes and then encodes its response.

W

Web cache
A web cache stores HTTP responses for reuse, reducing repeated transfers when freshness and validation rules permit.
The browser’s web cache supplies an unchanged image without fetching another full copy.
Webmail
Webmail is browser-based mailbox access using HTTP, normally HTTPS, while mail delivery between providers still uses SMTP.
The browser uses webmail over HTTPS to read a message that arrived at the provider through SMTP.

#

0-RTT data
0-RTT data is application data sent during resumed connection setup before a new round trip completes, with replay-related restrictions.
A resumed QUIC connection can send eligible 0-RTT data before waiting for the fresh server exchange.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started