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 7proxylabout.) 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:
- Write out the sockets interface in order —
socket,bind,listen,accepton the server;socket,connecton the client — and say what each call accomplishes. - Explain the difference between a listening descriptor and a connected descriptor, and why a server needs both.
- Use
getaddrinfocorrectly on both sides (includingAI_PASSIVE) and iterate its list so the program is dual-stack IPv4/IPv6 for free. - Build an iterative echo server and client on Lecture 18’s RIO package, and state the limitation that motivates concurrency.
- 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. - 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_writenare 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
| Section | Idea | Demo in code/lecture20/ |
|---|---|---|
| §1–§2 | the sockets interface, both sides | netutil.c |
| §3 | an iterative echo server and client | echoserver.c, echoclient.c |
| §4 | HTTP on the wire | http_client.c |
| §4–§5 | a static web server; errors | tiny_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 */
socketcreates an unconnected endpoint. Its three arguments come straight from theaddrinfoentry — which is the practical reason to usegetaddrinfo: it fills in family/type/protocol consistently, so the same code works for IPv4 and IPv6.connectperforms 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
localhostresolving to::1before127.0.0.1; a client that used only the first entry would fail on a host without IPv6. A failedconnectalso 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);
bindclaims an address and port for this socket: “traffic sent here is mine”. It is what makes a server findable.listenconverts the socket from “could be a client” into a passive, listening socket. The kernel then completes handshakes on your behalf and queues up tobacklogestablished connections for you.SO_REUSEADDRlets you bind the port again immediately after the server exits. Without it the port lingers in TCP’sTIME_WAITstate for a minute or two and a quick restart fails with “address already in use” — the most common annoyance in socket programming.AI_PASSIVEtellsgetaddrinfo“I intend tobindthis, not connect to it”. With aNULLhost 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 descriptor | Connected descriptor | |
|---|---|---|
| Created by | socket+bind+listen | accept (server) or connect (client) |
| Represents | a queue of connection requests | one conversation with one peer |
| You read/write it | never | always |
| How many | usually one per port | one 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
readalmost 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’srio_readlinebreturns 0. That is not an error; it is the message “I am done”. A client that forgets tocloseis 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.GETasks for a resource;POSTsubmits data;HEADasks for headers only. - Headers are lines of
Name: value.Hostis 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:
2xxsuccess,3xxredirect,4xxthe client’s fault (404 Not Found,403 Forbidden),5xxthe server’s fault (501 Not Implemented). Content-lengthsays exactly how many body bytes follow, letting the client read precisely the right amount;Content-type(a MIME type liketext/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:
accepta connection;- read the request line with
rio_readlineb; parsemethod,uri,version; - read and discard headers until the blank line;
- refuse anything but
GETwith501 Not Implemented; - map the URI to a path (
/→/index.htmlby convention) under a document root; statit (Lecture 18) — missing is404, not a regular file is403;- 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/passwdwould 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_REUSEADDRavoidsTIME_WAITrestart failures;AI_PASSIVEmarks an address for binding. - A listening descriptor is a queue of connection requests and is never read or written;
acceptreturns a connected descriptor for one conversation. One listening socket, many connected ones. - Iterate the
getaddrinfolist. Measured:localhostyields::1before127.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
closearrives 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-typeandContent-length. A static server maps a URI to a file andstats 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
acceptreturns. - Using only the first
getaddrinforesult. Walk the list, andclosea socket whoseconnectfailed before trying the next. - Omitting
SO_REUSEADDR. Restarting the server then fails with “address already in use” untilTIME_WAITexpires. - Binding the wildcard address by accident.
NULL+AI_PASSIVElistens on every interface; pass a loopback host if the service should be local. - Assuming one
readgets 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.
closeeach one after serving; a server that does not will exhaust its descriptor table.
Exercises
-
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. -
Two descriptors. A server has
listenfdand three clients connected. How many descriptors are in play, and which may be read?Answer
Four: 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.) -
Why the loop?
getaddrinfo("localhost","15213",…)returns::1then127.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. -
TIME_WAIT. You kill your server and restart it immediately;
bindfails with “address already in use” although nothing is listening. Why, and which one line fixes it?Answer
The 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. -
The hang. A client sends
GET / HTTP/1.0\r\nHost: x\r\nand then waits for a reply. Nothing happens. Why?Answer
It 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`. -
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. -
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?
Answer
It 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.
The related lab
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
tinyserver) and practice problems 11.5–11.11. §11.6’stiny.cis the reference static server;tiny_server.chere is an independent implementation in the same spirit. man 2 socket,man 2 bind,man 2 listen,man 2 accept,man 3 getaddrinfo— and thegetaddrinfomanual’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 | 缓存 |