Sockets
socket/bind/listen/accept/connect, TCP echo, network byte order, UDP and multi-client server models.
The socket API
The previous topic left the network inside the kernel: headers, the TCP handshake, retransmission and congestion control all happen without the process seeing them. What the process sees is a socket — a file descriptor for one end of a connection, driven by a handful of system calls. Compared with a pipe, a socket keeps the useful part (an fd that read/write work on) and fixes three failures: it can carry a network address, it is bidirectional, and the kernel’s TCP/IP stack can carry its bytes to another machine.
Key idea. A server creates a socket, binds it to a well-known address and marks it listening. The kernel then completes TCP handshakes and queues finished connections; accept takes one from the queue and returns a new descriptor so the listening socket stays free. A client creates a socket and calls connect, which runs the handshake. After that the two connected descriptors behave like a two-way pipe between two machines.
| Call | Who | Role | Blocks? |
|---|---|---|---|
socket(domain, type, 0) |
both | Create an unconnected socket; AF_INET+SOCK_STREAM = TCP/IPv4, SOCK_DGRAM = UDP |
no |
bind |
server | Attach a local address and port | no |
listen(fd, backlog) |
server | Passive mode; queue up to about backlog finished connections |
no |
accept |
server | New fd for one finished connection | while queue empty |
connect |
client | Ephemeral local port + three-way handshake | until handshake ends |
send/recv (or write/read) |
both | Copy into/out of kernel buffers | send full / recv empty |
close |
both | Release the fd; last close on TCP sends FIN | no |
getaddrinfo turns a host/service name into addresses for socket/connect/bind (IPv4 and IPv6). The Berkeley sockets API from the early 1980s is now POSIX; every call above is a system call or a thin wrapper.
Addresses use a generic struct sockaddr plus a length. For IPv4, sockaddr_in holds sin_family = AF_INET, sin_port and sin_addr.s_addr — both port and address in network byte order (big-endian). Example for loopback echo on port 8080: htons(8080) stores bytes 1f 90, and htonl(INADDR_LOOPBACK) stores 7f 00 00 01.
On a TCP echo over loopback the kernels, not the processes, perform the handshake. The server calls socket → bind → listen, then blocks in accept. The client’s connect makes its kernel send SYN; the server answers SYN+ACK; the client ACKs. Only then does connect return 0 and accept return a new connected fd. Fourteen bytes of payload can then go to the server and back; the client’s close sends FIN, and the server’s recv returns 0 — end of stream, exactly as a pipe’s read returns 0 when every writer has closed. Connections complete and queue even while the server is busy; Linux caps the listen backlog (default 4096 since Linux 5.4). If nothing listens, SYN meets RST and connect fails with ECONNREFUSED. After close, TIME_WAIT holds the address–port pair, so servers often set SO_REUSEADDR before bind.
TCP delivers a byte stream, not messages. Two send calls of 100 bytes may arrive as one recv of 200 or as many pieces; send may accept fewer bytes than offered. Every TCP program therefore loops until all intended bytes move, and frames messages with a delimiter (HTTP/1.1 headers end in \r\n) or a length prefix. A length-prefixed "hello" is nine bytes: 00 00 00 05 then 68 65 6c 6c 6f. Writing to a peer that already closed raises SIGPIPE by default; servers ignore it and check EPIPE, or use MSG_NOSIGNAL / SO_NOSIGPIPE.
Byte order and UDP
Protocol headers store multi-byte numbers big-endian. Most CPUs today (x86-64, ARM, RISC-V) are little-endian, so four conversion helpers exist — and on a big-endian host they are no-ops:
htons/htonl— host → network for 16-bit ports and 32-bit IPv4 addresses;ntohs/ntohl— network → host.
Worked example. Port sits in little-endian memory as bytes 90 1f. htons(8080) yields 1f 90 for the TCP header. Forgetting htons puts 90 1f on the wire; peers read and talk to the wrong port with no error. inet_pton on 192.168.10.77 yields bytes c0 a8 0a 4d; ntohl turns them into 0xC0A80A4D. Rule: every number that enters a sockaddr or header goes through hton*; every number read back goes through ntoh*. Payload byte order is the application’s problem — length prefixes need the same care.
A UDP socket uses SOCK_DGRAM: no listen, no accept, no handshake. The sender names the peer in each sendto; recvfrom returns one datagram and who sent it. Boundaries survive: sending ab then cde then 10 bytes yields receives of 2, then 3, never 5; a 4-byte buffer on a 10-byte datagram returns 4 and discards the rest. Delivery is not guaranteed. Over IPv4 the UDP payload maximum is bytes, but anything larger than the path MTU — bytes of UDP payload on Ethernet — fragments, and losing one fragment loses the datagram. connect on UDP only sets a default destination so plain send/recv work; no packet is sent by that call alone.
Many clients
A server that loops on accept still serves one client at a time: while it blocks in recv for A, B waits in the listen queue. Four standard answers exist.
- Process per connection. After
accept,fork; the child serves and exits, the parent closes its copy of the connected fd and returns toaccept. Isolation is strong; cost is a process per client.SIGCHLD→SIG_IGNlets the kernel reap children so zombies do not accumulate. - Thread per connection. Same shape with
pthread_create. Cheaper creation and shared memory (so shared counters need locks). Tens of thousands of idle connections still mean tens of thousands of stacks. select/poll. One thread asks which fds are ready, then callsaccept/recvonly on those.selectuses bit sets capped byFD_SETSIZE(1024 on Linux), so it cannot watch fd ≥ 1024. Both pass the whole list every call; cost grows with all connections, not with ready ones.epoll/kqueue. Register each fd once; each wait returns only the ready set. With 10,000 connections and 10 ready,pollchecks all 10,000 whileepoll_waitreports the 10 — the C10K answer (Kegel, ~1999). nginx and language async runtimes (asyncio) sit on this model, usually one loop per core, with non-blocking sockets so a full send buffer returnsEAGAINinstead of stalling the loop.
accept always yields a new fd; the listener remains. Most applications never write this in raw C — language runtimes wrap the same syscalls. Next — High-level languages and the OS: how Python and friends call them.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.