Lecture 20 · Network programming II

Introduction to Computer Systems · Lecture 20。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 20 (Nov 12), slide deck netprog2. Reading: CS:APP3e §11.4–§11.6. (Lab 6 due, Lab 7 proxylab out.) Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (macOS). All four programs are real network programs on the loopback interface; nothing is exposed to the network and nothing is architecture-specific. Code: code/lecture20/. Reading time: ~90 minutes; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write out the sockets interface in order — socket, bind, listen, accept on the server; socket, connect on the client — and say what each call accomplishes.
  2. Explain the difference between a listening descriptor and a connected descriptor, and why a server needs both.
  3. Use getaddrinfo correctly on both sides (including AI_PASSIVE) and iterate its list so the program is dual-stack IPv4/IPv6 for free.
  4. Build an iterative echo server and client on Lecture 18’s RIO package, and state the limitation that motivates concurrency.
  5. Read and write an HTTP transaction by hand: the request line, headers, the blank line, the status line, Content-type/Content-length, and a body.
  6. Distinguish static from dynamic content, and explain what a proxy sits between and why it caches.

0.2 Prerequisites and scope

  • Lecture 19: addresses, byte order, DNS and getaddrinfo. This lecture spends what that one earned.
  • Lecture 18: descriptors and RIO. A connected socket is a descriptor, so rio_readlineb/rio_writen are used unchanged — and short counts are now the normal case.
  • Lecture 16: fork/wait; Lecture 17: signals. A production server needs both (and Lecture 21 adds threads).
  • In scope: CS:APP §11.4–§11.6 — the sockets interface, echo client/server, Web basics, HTTP, static vs dynamic content, proxies.
  • Out of scope / policy: concurrency (Lecture 21), and the proxy lab’s deliverable. These notes explain proxies but contain no proxy code.

0.3 Section → code map

SectionIdeaDemo in code/lecture20/
§1–§2the sockets interface, both sidesnetutil.c
§3an iterative echo server and clientechoserver.c, echoclient.c
§4HTTP on the wirehttp_client.c
§4–§5a static web server; errorstiny_server.c, www/

1. The sockets interface

A socket is an endpoint of a connection that, to your program, is simply a descriptor. The whole interface exists to produce that descriptor; once you have it, you are back in Lecture 18.

The two sides are asymmetric. A server must become findable and then wait; a client must find the server and reach out:

  SERVER                                    CLIENT
  ──────                                    ──────
  getaddrinfo()   what address is mine?     getaddrinfo()   what is theirs?
  socket()        make an endpoint          socket()        make an endpoint
  bind()          claim address+port
  listen()        become passive
  accept()        wait for a client   ◀───  connect()       3-way handshake
      │                                         │
      └──── connfd ──────  read/write  ─────── clientfd ────┘

Both columns are the same every time, so they are packaged once in netutil.c: open_listenfd(port) and open_clientfd(host, port). Read that file alongside this section — it is the lecture’s centerpiece, with every call commented in place.

1.1 The client side

/* for each address the name resolves to … */
fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (connect(fd, p->ai_addr, p->ai_addrlen) == 0) break;   /* success */
close(fd);                                                /* else try the next */
  • socket creates an unconnected endpoint. Its three arguments come straight from the addrinfo entry — which is the practical reason to use getaddrinfo: it fills in family/type/protocol consistently, so the same code works for IPv4 and IPv6.
  • connect performs TCP’s three-way handshake and blocks until the connection is established, refused, or times out. On success the descriptor is a full-duplex byte stream.
  • The loop is not optional. Lecture 19 measured localhost resolving to ::1 before 127.0.0.1; a client that used only the first entry would fail on a host without IPv6. A failed connect also leaves the socket unusable, so it must be closed before trying the next address, never reused.

1.2 The server side

fd = socket(...);
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
bind(fd, p->ai_addr, p->ai_addrlen);
listen(fd, LISTEN_BACKLOG);
  • bind claims an address and port for this socket: “traffic sent here is mine”. It is what makes a server findable.
  • listen converts the socket from “could be a client” into a passive, listening socket. The kernel then completes handshakes on your behalf and queues up to backlog established connections for you.
  • SO_REUSEADDR lets you bind the port again immediately after the server exits. Without it the port lingers in TCP’s TIME_WAIT state for a minute or two and a quick restart fails with “address already in use” — the most common annoyance in socket programming.
  • AI_PASSIVE tells getaddrinfo “I intend to bind this, not connect to it”. With a NULL host it yields the wildcard address and listens on every interface. These demos deliberately pass "localhost" instead, binding loopback only, so a teaching program never opens a port to the network.

1.3 Two kinds of descriptor

This distinction causes more confusion than anything else in the chapter:

Listening descriptorConnected descriptor
Created bysocket+bind+listenaccept (server) or connect (client)
Representsa queue of connection requestsone conversation with one peer
You read/write itneveralways
How manyusually one per portone per active client

accept is the bridge: it removes a completed connection from the listening socket’s queue and returns a brand-new descriptor for that single client. The listening descriptor stays open and keeps queueing others. This is precisely what lets one server hold many simultaneous conversations — and what Lecture 21 exploits.


2. A socket is just a descriptor

Once accept or connect returns, every network-specific idea disappears. The echo server reads its client with the same call that read a file in Lecture 18:

rio_t rio;
rio_readinitb(&rio, connfd);        /* a SOCKET, not a file -- same code */
while ((n = rio_readlineb(&rio, buf, MAXLINE)) > 0)
    rio_writen(connfd, buf, n);

Two Lecture 18 lessons become essential rather than merely good practice:

  • Short counts are now the rule. Data arrives in whatever pieces the network delivers, so a single read almost never returns what you asked for. Every transfer must use a RIO-style loop.
  • EOF is how a conversation ends. When the client calls close, the server’s rio_readlineb returns 0. That is not an error; it is the message “I am done”. A client that forgets to close is why a server sometimes appears to hang forever.

Use RIO, not standard I/O, on sockets: a socket is read and written through one descriptor, and standard I/O’s rules for interleaving reads and writes on a single stream are restrictive and easy to violate.


3. The echo server and client

echoserver.c and echoclient.c are a complete, working pair. An echo server does nothing useful, which is the point: it shows the shape of a server with no application logic in the way.

[client] connected to localhost:15213 (clientfd=5)
[client] sent "hello, sockets"                   got back "hello, sockets"
[client] sent "a socket is just a descriptor"    got back "a socket is just a descriptor"
[client] sent "15213"                            got back "15213"
[client] closed the connection (the server now sees EOF)

----- the server's own transcript -----
[server] listening on 127.0.0.1:15213 (listenfd=5), will serve 1 connection(s)
[server] connection 1 accepted from ::1:61750 (connfd=6)
  served 3 line(s), 51 byte(s), then the client closed (EOF)
[server] closed connfd=6

Three things in that transcript are worth stopping on.

The connection went over IPv6. The server logs the peer as ::1, not 127.0.0.1 — yet neither program mentions IPv6 anywhere. Because open_clientfd used AF_UNSPEC and walked the address list, and localhost’s IPv6 address comes first, the program is dual-stack for free. Hard-coding AF_INET would have worked here too, but would break on an IPv6-only network; the loop costs five lines and removes the whole problem.

listenfd=5, not 3. Lecture 18 established that descriptors are handed out lowest-first, so the first socket “should” be 3. Measuring showed why it is not: on macOS, getaddrinfo permanently occupies descriptors 3 and 4 (its connection to the system resolver) and does not release them on freeaddrinfo. The rule is intact — what changed is that a library opened descriptors behind the program’s back. Descriptors are a process-wide resource shared with libc.

The server is iterative. It serves one client to completion before accepting the next. That is simple and strictly ordered, and it is also the server’s fatal flaw: one slow or malicious client blocks every other client indefinitely. Fixing that is the entire subject of Lecture 21 (process-, event- and thread-based concurrency).


4. The Web: HTTP, and a server that speaks it

4.1 HTTP is text

A web server is an echo server with a protocol. Replace “echo the line” with “parse a request, find the file, send a response” and you have the Web. The protocol is text you could type by hand:

request                           response
───────                           ────────
GET /index.html HTTP/1.0          HTTP/1.0 200 OK
Host: localhost                   Content-type: text/html
User-Agent: …                     Content-length: 396
Connection: close                 (blank line)
(blank line)                      <the file's bytes>
  • The request line is METHOD URI VERSION. GET asks for a resource; POST submits data; HEAD asks for headers only.
  • Headers are lines of Name: value. Host is required by HTTP/1.1 and polite in 1.0, because one machine can serve many sites and the server must know which was requested.
  • The blank line ends the headers and is the single most important byte sequence in the protocol. Omit it and the server waits forever for more headers while the client waits for a reply — the classic beginner hang.
  • The status line carries a numeric code: 2xx success, 3xx redirect, 4xx the client’s fault (404 Not Found, 403 Forbidden), 5xx the server’s fault (501 Not Implemented).
  • Content-length says exactly how many body bytes follow, letting the client read precisely the right amount; Content-type (a MIME type like text/html) tells it how to interpret them.

4.2 Seeing it raw

http_client.c writes a request by hand and prints the reply verbatim:

=== the request we send (89 bytes) ===
GET / HTTP/1.0
Host: localhost
User-Agent: 15213-http-client/1.0
Connection: close

=== the response status line ===
HTTP/1.0 200 OK
=== the response headers ===
Server: tiny_server
Content-type: text/html
Content-length: 396
=== (3 header(s); blank line seen -> body follows) ===
…
=== end of body (396 bytes, Content-length said 396: match) ===

The body was read with RIO, in two legitimate ways: read exactly Content-length bytes when it is given, or read until EOF (valid here because the client asked for Connection: close). Asking for a missing file shows the error path is the same protocol, not a broken connection:

=== the response status line ===
HTTP/1.0 404 Not Found
Content-length: 186

4.3 A static web server

tiny_server.c is ~200 commented lines and does the whole job:

  1. accept a connection;
  2. read the request line with rio_readlineb; parse method, uri, version;
  3. read and discard headers until the blank line;
  4. refuse anything but GET with 501 Not Implemented;
  5. map the URI to a path (/ → /index.html by convention) under a document root;
  6. stat it (Lecture 18) — missing is 404, not a regular file is 403;
  7. send the status line, Content-type, Content-length, a blank line, then copy the file to the socket with the robust loop of Lecture 18.

Its own log shows the mapping happening:

[tiny] request 1 from ::1:61751
  request line: GET / HTTP/1.0
  (3 header line(s) read, then the blank line)
  -> 200 OK, serving www/index.html (396 bytes, text/html)
[tiny] request 2 from ::1:61752
  request line: GET /nope.txt HTTP/1.0
  -> 404 (no such file: www/nope.txt)

One security line that is not optional. The server refuses any URI containing ..:

if (strstr(uri, "..")) { serve_error(fd, "403", "Forbidden", …); return; }

Without it, GET /../../etc/passwd would escape the document root and serve arbitrary files. Any server that builds a filesystem path out of untrusted input must validate it first. This is the networking face of Lecture 6’s lesson: data from outside your program is not to be trusted.

4.4 Static vs dynamic content

Static content is a file the server returns unchanged — what tiny_server does. Dynamic content is generated per request by running a program, so the response can depend on the query, the user or the time. The classic mechanism is CGI: the server forks, sets the query string in an environment variable, dup2s the connected socket onto the child’s stdout, and execves the program — so whatever the program prints goes straight to the client. That is Lectures 16 and 18 reused verbatim: fork + dup2 + exec, exactly as for shell redirection. (Modern servers mostly use long-lived application processes instead of a fork per request, but the plumbing idea is the same.)


5. Proxies

A proxy is a program that is a server to its clients and a client to other servers. A browser sends it a request; the proxy forwards that request to the origin server, reads the response, and relays it back.

  browser  ──request──▶  PROXY  ──request──▶  origin server
           ◀─response──  (server to the      ◀─response──
                          browser, client
                          to the origin)

Proxies exist because sitting in the middle is useful:

  • Caching. Keep a copy of a response and serve the next identical request from memory — less latency for the user and less load on the origin. This is the main reason, and the reason the Web scales.
  • Access control and filtering, e.g. at an organization’s boundary.
  • Anonymization, hiding the client’s identity from the origin.
  • Translation, adapting content for a device or a protocol.

Note that the proxy demonstrates the client/server asymmetry is about roles, not machines: the same program plays both at once, which is why the sockets interface gives you both columns.

Lab policy. The proxy lab asks you to build a caching, concurrent web proxy. That is your own work, so these notes and the code folder contain no proxy code — only the concepts above, plus a static origin server and an HTTP client you can test against. The code you need is the sockets interface of §1, the RIO package of Lecture 18, and the concurrency of Lecture 21.


Summary

  • The sockets interface produces a descriptor: server = getaddrinfo/socket/bind/listen/accept; client = getaddrinfo/socket/connect. SO_REUSEADDR avoids TIME_WAIT restart failures; AI_PASSIVE marks an address for binding.
  • A listening descriptor is a queue of connection requests and is never read or written; accept returns a connected descriptor for one conversation. One listening socket, many connected ones.
  • Iterate the getaddrinfo list. Measured: localhost yields ::1 before 127.0.0.1, so the demo connected over IPv6 without either program mentioning it. AF_UNSPEC + the loop = dual-stack for free.
  • Once connected, a socket is just a descriptor: Lecture 18’s RIO works unchanged, short counts are now the norm, and the peer’s close arrives as EOF (0).
  • An iterative server serves one client at a time — simple, and blocked by any slow client. That limitation motivates Lecture 21.
  • HTTP is text: request line, headers, blank line, body; status codes 2xx–5xx; Content-type and Content-length. A static server maps a URI to a file and stats it; dynamic content runs a program (CGI = fork + dup2 + exec). Validate untrusted paths (..).
  • A proxy is a server to its clients and a client to origin servers; it exists mainly to cache.

Common pitfalls

  • Reading or writing the listening descriptor. It is a queue; use the descriptor accept returns.
  • Using only the first getaddrinfo result. Walk the list, and close a socket whose connect failed before trying the next.
  • Omitting SO_REUSEADDR. Restarting the server then fails with “address already in use” until TIME_WAIT expires.
  • Binding the wildcard address by accident. NULL + AI_PASSIVE listens on every interface; pass a loopback host if the service should be local.
  • Assuming one read gets the whole message. Sockets short-count freely; use RIO, and treat 0 as EOF.
  • Forgetting the blank line after HTTP headers (either side) — both ends then wait forever.
  • Forgetting Content-length, or disagreeing with it. Clients that trust it will read too few or too many bytes.
  • Using standard I/O on a socket. Use RIO: one bidirectional descriptor breaks standard I/O’s interleaving rules.
  • Building a path from a URI without validating it. .. escapes the document root.
  • Leaking connected descriptors. close each one after serving; a server that does not will exhaust its descriptor table.

Exercises

  1. Which call? Name the one call that turns a socket into a server that the kernel will complete handshakes for, and the one that hands you a conversation.

    Answer`listen()` makes the socket **passive** (the kernel completes handshakes and queues established connections). `accept()` removes one from the queue and returns a new **connected** descriptor. `bind()` only claims the address; without `listen` nothing is accepted.
  2. Two descriptors. A server has listenfd and three clients connected. How many descriptors are in play, and which may be read?

    AnswerFour: one listening plus three connected. Only the three **connected** ones may be read or written; the listening descriptor is a request queue. (Plus stdin/stdout/stderr and whatever libraries hold — on macOS `getaddrinfo` keeps two.)
  3. Why the loop? getaddrinfo("localhost","15213",…) returns ::1 then 127.0.0.1. Your client uses only the first entry and the machine has IPv6 disabled. What happens, and what is the fix?

    Answer`connect` to `::1` fails (network unreachable / connection refused) and the client reports failure even though the server is reachable at `127.0.0.1`. The fix is to iterate: on failure, `close` that socket and try the next address, failing only when the list is exhausted.
  4. TIME_WAIT. You kill your server and restart it immediately; bind fails with “address already in use” although nothing is listening. Why, and which one line fixes it?

    AnswerThe old connection's endpoint sits in TCP's `TIME_WAIT` state (a minute or two) so late duplicate packets cannot be misdelivered, and the port is still considered in use. `setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))` before `bind` permits the rebind.
  5. The hang. A client sends GET / HTTP/1.0\r\nHost: x\r\n and then waits for a reply. Nothing happens. Why?

    AnswerIt never sent the **blank line** (`\r\n`) that terminates the headers, so the server is still reading header lines and will not respond; the client is waiting for a response that cannot come. Send the final `\r\n`.
  6. Static vs dynamic. Describe the three Lecture-16/18 calls a server uses to run a CGI program and get its output to the client.

    Answer`fork` a child; in the child `dup2(connfd, STDOUT_FILENO)` so the program's standard output *is* the socket; then `execve` the CGI program (with the query string passed in the environment). Whatever the program prints goes straight to the client. Identical machinery to shell redirection.
  7. Proxy roles. A caching proxy receives a request for a page it already holds. Which role is it playing, and how many TCP connections exist?

    AnswerIt acts purely as a **server** (to the browser) and serves from its cache, so it needs **one** connection — browser↔proxy — and makes no request to the origin. On a cache miss it would also act as a **client**, opening a second connection to the origin server, for two in total.

Lab 7, proxylab, is assigned around this lecture: a concurrent, caching web proxy built from exactly this material plus Lecture 21’s concurrency. Per the course’s academic-integrity policy these notes contain no lab solutions — no proxy code of any kind. What the code folder provides is the infrastructure the lab’s handout also assumes: a documented sockets interface, an RIO package, a static origin server to test against, and an HTTP client that prints raw bytes so you can see what your own program sends and receives.

Further reading

  • CS:APP3e §11.4–§11.6 (the sockets interface, Web servers, the tiny server) and practice problems 11.5–11.11. §11.6’s tiny.c is the reference static server; tiny_server.c here is an independent implementation in the same spirit.
  • man 2 socket, man 2 bind, man 2 listen, man 2 accept, man 3 getaddrinfo — and the getaddrinfo manual’s example client/server, which is the canonical “walk the list” code.
  • RFC 1945 (HTTP/1.0) and RFC 7230–7235 (HTTP/1.1) — surprisingly readable; the request/response grammar is a page.
  • Stevens, Fenner & Rudoff, UNIX Network Programming, vol. 1 — the definitive reference on sockets.

Preview of Lecture 21: Concurrent programming

The echo server’s flaw is now the agenda. Lecture 21 makes a server handle many clients at once, three ways: process-based (a fork per connection — Lectures 16–17’s SIGCHLD reaping becomes essential), event-based (one process multiplexing with select/poll), and thread-based (one thread per connection, sharing an address space). It compares their costs, introduces threads as the unit of concurrency, and sets up the sharing problems — races and synchronization — that occupy Lectures 22–24.


术语表 (Glossary, English → 中文)

English中文
socket套接字
sockets interface / API套接字接口
socket创建套接字
bind绑定地址端口
listen监听
accept接受连接
connect发起连接
listening descriptor监听描述符
connected descriptor已连接描述符
backlog (connection queue)连接队列(积压)
three-way handshake三次握手
TIME_WAIT等待超时状态
SO_REUSEADDR地址复用选项
setsockopt设置套接字选项
AI_PASSIVE用于绑定的地址标志
wildcard address通配地址
loopback interface回环接口
dual-stack (IPv4/IPv6)双栈
getpeername获取对端地址
iterative server迭代式服务器
concurrent server并发服务器
echo server / client回显服务器 / 客户端
byte stream字节流
EOF (connection closed)连接结束
World Wide Web万维网
HTTP (Hypertext Transfer Protocol)超文本传输协议
URL / URI统一资源定位符 / 标识符
request line请求行
header / blank line首部行 / 空行
status line / status code状态行 / 状态码
GET / POST / HEAD请求方法
Content-type (MIME type)内容类型
Content-length内容长度
Host header主机首部
404 Not Found / 403 Forbidden / 501 Not Implemented未找到 / 禁止访问 / 未实现
static content静态内容
dynamic content动态内容
CGI (Common Gateway Interface)通用网关接口
document root文档根目录
path traversal路径穿越
proxy代理
origin server源服务器
caching缓存
← 返回课程目录