Previous: Operating Systems Reading map Next: Parallel Programming
Volume II: Systems Programming (Chapter 6)Code & tests Chapter diagrams Download editable SVGs
A computer network is a way for computers to exchange data. Modern networks are normally packet-switched: data is split into small packets, each packet has addressing information, and network equipment tries to deliver each packet independently.
Chapter Map
socketpairselect, state machines, nonblocking connect,
and pselectA network can be described at many levels: wires or radio links, frames on a local segment, packets routed between networks, streams between applications, and finally the application protocol itself. The important practical idea is that each level hides details from the level above it.
computer network: connected computers able to exchange data
Historically, communication systems can be grouped like this:
| Kind of network | Main idea | Example |
|---|---|---|
| Fixed connections | Endpoints are permanently connected by a fixed arrangement | Simple field telephones |
| Circuit switching | A connection is established, used, then disconnected | Traditional telephone network |
| Packet switching | Data is split into addressed packets sent through the net | Modern computer networks |
Computer networks discussed here use packet switching. A packet can be lost, duplicated, delayed, or delivered out of order unless higher-level protocols add stronger guarantees.
Physical media vary widely:
| Medium | Notes |
|---|---|
| Coaxial Ethernet | Older bus-like Ethernet; collisions and broken terminators mattered |
| Twisted pair | Common wired Ethernet cabling |
| Fiber optic cable | Light pulses, useful for distance and high bandwidth |
| WiFi | Radio; shared air, channels, interference, authentication |
| Cellular networks | Wide-area radio network managed by an operator |
| Serial lines | Simple point-to-point links such as RS-232 |
Basic local-network devices:
| Device | Role |
|---|---|
| Hub | Repeats incoming signals to all other ports; mostly historical |
| Switch | Learns which MAC addresses are behind which ports and forwards frames |
| Router/gateway | Forwards packets between different networks |
With switched Ethernet, a frame is sent only toward the port where the switch believes the destination MAC address lives. This removes the ordinary collision behavior of old shared-bus Ethernet.
communication networks can use fixed connections
circuit switching:
packet switching:
chapter's scope: packet-switched computer networks
physical media vary widely
applications can often ignore the physical transmission technology
physical access still affects security assumptions
physical topology and logical communication topology are different
historical Ethernet used coaxial cable
coaxial Ethernet bus:
bus cable required correct termination at both ends
historical twisted-pair Ethernet replaced the coaxial bus
switches replaced hubs
switch maintains address-to-port information
manufacturing made simple switches inexpensive
historically, hubs and especially switches were expensive
coaxial bus -> twisted-pair hub:
network cards sometimes supported both coax and twisted pair
for programming, classify networks by properties visible to programs
TCP/IP hides many differences between local and remote communication
network boundaries can be administrative as well as technical
one logical link can serve several computers
point-to-point link connects exactly two endpoints
multipoint links need a way to select the next recipient on the link
networking does not require a dedicated network card
network hardware need not be a separate expansion card
network interface: the connection point used to exchange data with other computers
interface can also be a software abstraction
A gateway or router connects networks. It receives packets from one network and forwards them toward another network according to routing rules.
Routing is based on destinations, not on a permanent circuit. A host or router usually has a routing table containing rules such as:
| Destination kind | Action |
|---|---|
| Local network | Send directly through the local interface |
| Specific remote network | Send to a named gateway |
| Default route | Send everything else to the default gateway |
The default route is the rule that normally sends traffic toward the Internet. More specific routes take precedence over the default route.
Routers often do more than forwarding:
Routing can involve several gateways. A packet may move from a local network to a home router, then to an ISP router, then through more provider networks, until it reaches a network that knows the final destination.
one large link has scaling limits
large shared networks also complicate administration and isolation
one computer can have several network interfaces
router/gateway forwards packets between networks
home Internet router is also a computer
gateway is a transfer point between links
example: two separate home LANs
residents want communication between the LANs
joining switches could make one larger LAN
Boris and Dmitry establish a radio link and act as gateways
configure other hosts' routes toward the relevant gateway
add an Internet router to the first LAN
extend Internet access to the second LAN
possible extensions:
A protocol is a set of rules that lets participants communicate. In network programming, protocol specifications tell implementers how packets, messages, addresses, state transitions, and error cases must be handled.
The OSI model is a teaching model with seven layers:
| Layer | Main concern |
|---|---|
| Physical | Signals, wires, radio, connectors, frequencies |
| Data link | Frames on one local link, MAC addresses, error detection |
| Network | Packet addressing and routing between networks |
| Transport | End-to-end delivery service for applications |
| Session | Logical session ordering and lifetime |
| Presentation | Data representation: encodings, formats, conversions |
| Application | Application-specific commands and data |
The Internet does not implement OSI literally. TCP/IP grew as a practical set of protocols, but the OSI layers are still useful vocabulary.
Example stack for a web request:
| Layer-ish role | Example protocol or mechanism |
|---|---|
| Physical/link | Ethernet, WiFi, cellular data |
| Network | IP |
| Transport | TCP |
| Application | HTTP or HTTPS |
| Representation | HTML, CSS, image formats, text encodings, TLS details |
protocol: agreements participants follow to understand one another
protocol specification tells implementers how to interoperate
OSI = Open Systems Interconnection; seven-layer reference model
mnemonic from top to bottom: All People Seem To Need Data Processing
author contrasts committee-designed layering with TCP/IP's practical development
Ethernet over twisted pair, such as 100BASE-TX, defines
both electrical details and frame format. WiFi
(IEEE 802.11) defines radio behavior, channel use, and
frame exchange in a shared radio environment. Cellular networks have
their own protocol stacks, and simple serial lines such as RS-232 can
also be used as low-level links.
At the link layer, network interfaces identify each other with MAC addresses. A MAC address is usually a six-byte value often written like:
00:1f:c6:65:42:48
MAC addresses belong to link-layer frames, not to Internet routing. IP routing uses IP addresses. A host that wants to send an IP packet on a local Ethernet or WiFi segment must know which MAC address should receive the frame.
ARP connects IPv4 addresses to local MAC addresses:
| Step | Action |
|---|---|
| 1 | Host broadcasts: who has this IPv4 address? |
| 2 | Owner replies with its MAC address |
| 3 | Sender caches the mapping and sends frames to that address |
This only works on the local link. If the destination is not local, the sender looks up the MAC address of the next gateway, not of the final remote host.
physical protocol depends on the actual connection
Wi-Fi uses the IEEE 802.11 family
cellular access adds its own radio and network protocols
RS-232 is a simpler physical-interface example
Ethernet/Wi-Fi interfaces use link-layer MAC addresses
manufacturer address allocations do not all use the same prefix length
effective MAC address can differ from the factory address
ARP resolves an IPv4 next-hop address to a link-layer address
point-to-point links do not need ARP to choose among several peers
IP is the network-layer protocol used to route packets between networks. Classic IPv4 addresses are 32-bit values written as four decimal bytes:
192.168.10.12
An IP address is assigned to a network interface, not directly to a process. A host may have several interfaces and therefore several IP addresses.
IPv4 packet delivery is best effort:
| Property | Meaning |
|---|---|
| No guarantee | A packet may be lost |
| No ordering | Packets may arrive in a different order |
| No uniqueness | Duplicates are possible |
| Header checksum | IPv4 checks the header, not necessarily the payload |
IPv4 routing uses network prefixes. CIDR notation writes the prefix length after a slash:
| Prefix | Meaning |
|---|---|
192.168.10.0/24 |
First 24 bits are the network part |
10.0.0.0/8 |
First 8 bits are the network part |
0.0.0.0/0 |
Default route: every address matches |
Special IPv4 ranges are used in local networks and should not be routed on the public Internet:
| Range | Common use |
|---|---|
10.0.0.0/8 |
Private networks |
172.16.0.0/12 |
Private networks |
192.168.0.0/16 |
Private networks |
127.0.0.0/8 |
Loopback, usually 127.0.0.1 |
NAT lets many private hosts share one public address. It changes packet address and port fields at the gateway and keeps a table so replies can be mapped back to the internal host.
Etude 6.05 lists every subnet that contains a given address, from the
address itself (/32) down to /1. Each step
shortens the prefix by one bit and clears that bit of the address:
static void print_subnets(const int *inp)
{
int i, j, k, mask;
int ip[ip_length];
memcpy(ip, inp, sizeof(ip));
k = ip_length * bit_in_byte;
for (i = ip_length - 1; i >= 0; i--) {
for (mask = 1, j = 0; j < bit_in_byte; mask <<= 1, j++, k--) {
printf("%d.%d.%d.%d/%d\n", ip[0], ip[1], ip[2], ip[3], k);
ip[i] &= ~mask;
}
printf("\n");
}
}
$ ./subnets 192.168.1.130
192.168.1.130/32
192.168.1.130/31
192.168.1.128/30
192.168.1.128/29
192.168.1.128/28
192.168.1.128/27
192.168.1.128/26
192.168.1.128/25
192.168.1.0/24
...
128.0.0.0/1
IP provides network-layer packets, addresses, and forwarding
IP supports interconnection of heterogeneous networks
Internet consists of networks under many separate administrations
individual links and operators can disappear or change
alternative routes can preserve communication after failures
network host: a computer/end system participating in a network
IPv4 address: 32 bits, commonly written as four decimal octets
routing needs to describe sets of destinations compactly
prefix/subnet groups addresses sharing their first N bits
CIDR notation: network-address/prefix-length
ordinary IPv4 broadcast subnets reserve boundary addresses
/32 prefix selects exactly one IPv4 address
one address belongs to nested prefixes of every length
0.0.0.0/0 includes the entire IPv4 address space
assign contiguous prefixes to simplify routing
some IPv4 ranges have special meanings
224.0.0.0/4 is IPv4 multicast address space
multicast forwarding builds distribution paths
multicast also supports local control/routing protocols
private IPv4 ranges:
example LAN addressing:
separate radio link gets a separate subnet
Internet router's inside address: 192.168.12.100
two routing forms:
example interface names: eth0 for LAN, wlan0 for radio link
Anna/Vera need two different gateways
Boris connects two links
Dmitry's routes:
Internet router has an inside Ethernet interface and illustrative point-to-point wan0
routing alone does not make private source addresses globally usable
NAT translates private traffic using the router's external address
remote peer normally sees the NAT's external address
many-to-one NAT must distinguish simultaneous exchanges
radio-link subnet can also be advertised to ordinary hosts
routers can then be reached through their radio-interface addresses too
illustrative unnumbered point-to-point route arrangement:
longest-prefix match chooses the most specific matching route
more-specific local route overrides the broader aggregate
address conservation matters when the available allocation is small
compact example requirements:
choose aggregate 192.168.45.64/27: .64 through .95
Dmitry's LAN: 192.168.45.80/28
transit link: 192.168.45.76/30
subnet mask is another representation of prefix length
IPv4 TTL limits packet lifetime in router hops
MTU limits packet size on a link
IPv4 has 2^32 possible bit patterns
address scarcity motivated conservation and a replacement protocol
IPv6 addresses have 128 bits
transition requires compatibility across independently operated networks
book discusses IPv4 exhaustion, allocation restrictions, and possible address reuse
author speculates about IPv6's future and possible alternatives
At the transport level, the two main styles are datagrams and streams.
| Style | Internet protocol | Programmer sees |
|---|---|---|
| Datagram | UDP | Separate messages, each sent to an address |
| Stream | TCP | Bidirectional byte stream after connection setup |
UDP adds ports, length, and checksum information around application data. It does not promise delivery, order, or duplicate suppression. Applications that need reliability must implement acknowledgements, retries, numbering, and timeouts themselves.
TCP provides a reliable byte stream. The operating system and TCP implementation handle acknowledgements, retransmission, ordering, flow control, and connection state. The cost is complexity and the need to establish a connection before data exchange.
Ports identify application endpoints inside one host:
| Port range | Usual meaning |
|---|---|
1..1023 |
Privileged or well-known service ports |
1024..49151 |
Registered or ordinary service ports |
| Higher ports | Often used temporarily by clients |
A network endpoint for IPv4 TCP or UDP is the pair:
IP address + port number
IP delivers packets on a best-effort basis
splitting one object across datagrams requires reconstruction
minimal transport still needs two things
UDP = User Datagram Protocol
stream transport presents a bidirectional byte stream
TCP = Transmission Control Protocol
Application protocols define the commands, replies, state, and data formats used by real applications.
Examples:
| Protocol | Typical use |
|---|---|
| HTTP | Web requests and responses |
| SMTP | Mail transfer between mail systems |
| POP3/IMAP | Mail retrieval by mail clients |
| SSH | Secure remote login and command execution |
| DNS | Domain-name lookup |
The OSI session and presentation layers are often not separate Internet protocols. Web sessions, for example, are usually built above HTTP using cookies or tokens. Representation details such as UTF-8, HTML, JSON, PNG, and TLS also live in or above application protocols rather than in a distinct OSI layer.
session, presentation, and application responsibilities often overlap in real protocols
Internet applications organize sessions without a distinct universal session layer
web login session can span many requests and connections
data representation also relies on agreements
application protocols provide actual user services
client-server model:
many application protocols exchange text over a bidirectional stream
book's SMTP example sends one test message through a mail server
transcript distinguishes three sources of text
SMTP server starts by sending a greeting
greeting fields identify the service
EHLO introduces the client and requests extended SMTP capabilities
multiline EHLO response lists supported extensions
MAIL FROM supplies the envelope sender and begins a mail transaction
example successful reply: 250 2.1.0 Ok
SMTP clients interpret response codes, not decorative English wording
RCPT TO supplies an envelope recipient
open relay accepts mail from arbitrary senders for arbitrary destinations
unauthorized relaying can be rejected
unknown recipient can also be rejected
DATA requests permission to send the message content
SMTP content format:
DNS MX records identify mail exchangers for a domain
HTTP/1.1 example requests a site's root resource on TCP port 80
shell/telnet messages precede the actual HTTP request
blank line terminates the HTTP request headers
both protocols use three-digit response codes, with different category meanings
Humans prefer names over IP addresses such as:
example.org
Network routing uses addresses. DNS maps domain names to resource records, including IP addresses.
Important record types:
| Record | Meaning |
|---|---|
A |
IPv4 address |
AAAA |
IPv6 address |
MX |
Mail exchanger for a domain |
NS |
Authoritative name server |
CNAME |
Alias to another domain name |
PTR |
Reverse lookup from address to name |
DNS is hierarchical. A resolver asks name servers until it finds an answer or a negative result, and it caches answers according to their time-to-live values.
domain names are more convenient for people than numeric IP addresses
DNS = Domain Name System
'domain' means an area or collection in several technical contexts
names consist of dot-separated labels
resource records have class, type, content, and TTL
DNS domain is a subtree identified by a common name suffix
hierarchy distributes authority across independently operated servers
parent can delegate a child domain to another set of servers
zone data can be stored in a text zone file
$TTL sets the default record TTL in a zone file
important zone-file records:
wildcard record can provide answers for otherwise missing names
delegate example.stolyarov.info by adding NS records in its parent zone
glue avoids circular dependence when server names lie inside the delegated zone
root zone delegates top-level domains such as com, net, and info
root service uses 13 named server identities, a.root-servers.net through m.root-servers.net
recursive resolver caches records until their TTL expires
dig +trace lesiv.org:
m.root-servers.net
a0.org.afilias-nst.info
fortaleza.ns.porkbun.com
95.217.220.17
-----------------------------------------------------------------
m.root-servers.net
dig . NS
(DNS resolver tells)
;; ADDITIONAL SECTION:
m.root-servers.net. 402796 IN A 202.12.27.33
m.root-servers.net. 402858 IN AAAA 2001:dc3::35
-----------------------------------------------------------------
a0.org.afilias-nst.info
dig @m.root-servers.net a0.org.afilias-nst.info NS
a0.info.afilias-nst.info with IP
dig @a0.info.afilias-nst.info a0.org.afilias-nst.info NS
a0.dig.afilias-nst.info with IP
dig @a0.dig.afilias-nst.info a0.org.afilias-nst.info NS
;; ADDITIONAL SECTION:
a0.org.afilias-nst.info. 900 IN A 199.19.56.1
a0.org.afilias-nst.info. 900 IN AAAA 2001:500:e::1
dig @a0.org.afilias-nst.info lesiv.org NS
lesiv.org. 3600 IN NS salvador.ns.porkbun.com.
lesiv.org. 3600 IN NS curitiba.ns.porkbun.com.
lesiv.org. 3600 IN NS maceio.ns.porkbun.com.
lesiv.org. 3600 IN NS fortaleza.ns.porkbun.com.
-----------------------------------------------------------------
fortaleza.ns.porkbun.com
dig +trace fortaleza.ns.porkbun.com
m.root-servers.net with iP
b.gtld-servers.net with IP
dig @m.root-servers.net b.gtld-servers.net NS
;; ADDITIONAL SECTION:
b.gtld-servers.net. 172800 IN A 192.33.14.30
dig @b.gtld-servers.net ns-199.awsdns-24.com NS
dig @g-ns-25.awsdns-24.com ns-199.awsdns-24.com A
ns-199.awsdns-24.com. 172800 IN A 205.251.192.199
dig @ns-199.awsdns-24.com fortaleza.ns.porkbun.com NS
ns.porkbun.com. 86400 IN NS alagoas.ns.porkbun.com.
alagoas.ns.porkbun.com. 86400 IN A 162.159.0.229
dig @alagoas.ns.porkbun.com fortaleza.ns.porkbun.com IP
fortaleza.ns.porkbun.com. 900 IN A 162.159.8.140
-----------------------------------------------------------------
dig @fortaleza.ns.porkbun.com lesiv.org IP
lesiv.org. 600 IN A 95.217.220.17
Unix exposes network communication through sockets.
A socket is a kernel object associated with a file descriptor. It can be
closed with close, and many stream sockets can be used with
read and write.
socket system calls expose networking to user programs
Create a socket:
int socket(int family, int type, int protocol);
Common families:
| Family | Address form |
|---|---|
AF_INET |
IPv4 address plus port |
AF_INET6 |
IPv6 address plus port |
AF_UNIX |
Local filesystem pathname or local socket address |
Common interaction types:
| Type | Meaning | Usual protocol |
|---|---|---|
SOCK_DGRAM |
Datagram messages | UDP |
SOCK_STREAM |
Reliable bidirectional byte stream | TCP |
For the combinations used here, protocol can normally be
0; the family and type determine it. Explicit values such
as IPPROTO_TCP and IPPROTO_UDP also exist.
socket is a kernel communication endpoint
Unix socket is accessed through a file descriptor
address representation depends on protocol family
common socket API accommodates different families
socket type selects communication semantics
IP datagrams have finite size and no delivery/order guarantee
stream socket exposes an ordered bidirectional byte stream
create with socket(family, type, protocol)
socket arguments:
socket returns a new file descriptor on success
Bind a local address to a socket:
int bind(int sockfd, const struct sockaddr *addr, int addrlen);
For IPv4, the real structure is struct sockaddr_in, cast
to struct sockaddr * when passed to socket calls.
Important fields:
| Field | Meaning |
|---|---|
sin_family |
Address family, AF_INET |
sin_port |
Port in network byte order |
sin_addr.s_addr |
IPv4 address in network byte order |
Network byte order is big-endian. Use conversion functions:
unsigned int htonl(unsigned int hostlong);
unsigned short int htons(unsigned short int hostshort);
unsigned int ntohl(unsigned int netlong);
unsigned short int ntohs(unsigned short int netshort);
Convert a textual IPv4 address:
int inet_aton(const char *cp, struct in_addr *inp);
Address setup for a server listening on all local IPv4 interfaces:
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
Address setup for a client connecting to a known server:
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (!inet_aton("192.168.10.12", &addr.sin_addr)) {
/* invalid address string */
}
Use INADDR_LOOPBACK for the local host address
127.0.0.1 when a service should only accept local
connections.
bind assigns a local address to a socket
bind returns 0 on success, -1 on error
IPv4 uses struct sockaddr_in
address-family field identifies the concrete address representation
IP address identifies an interface/address on a host
network byte order is big-endian
function names encode direction and width
low-numbered ports traditionally require privilege
inet_aton converts textual IPv4 address to struct in_addr
inet_aton result:
inet_addr also converts IPv4 text
inet_addr result is already in network byte order
server can bind to all local IPv4 addresses
INADDR_ANY represents 0.0.0.0 for wildcard binding
struct sockaddr_in is declared through <netinet/in.h>
generic API takes struct sockaddr pointers
Unix-domain addresses use struct sockaddr_un from <sys/un.h>
pathname socket has a socket-type filesystem entry
pathname socket permission checks vary by OS
other families provide their own address structures
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res;
struct sockaddr_un addr;
sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket02.txt");
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res, ok;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
ok = inet_aton("172.26.100.39", &(addr.sin_addr));
if (!ok)
terminate("inet_aton");
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = inet_addr("172.26.100.39");
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int fd, res;
struct sockaddr_un addr;
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket05.t");
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
UDP sockets use sendto and recvfrom:
int sendto(int sockfd, const void *buf, int len, int flags,
const struct sockaddr *to, socklen_t tolen);
int recvfrom(int sockfd, void *buf, int len, int flags,
struct sockaddr *from, socklen_t *fromlen);
sendto sends one datagram to one address.
recvfrom receives one datagram and optionally tells you who
sent it.
Minimal UDP server shape:
int sd;
char buf[512];
struct sockaddr_in addr, peer;
socklen_t peer_len;
int n;
sd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind");
exit(1);
}
for (;;) {
peer_len = sizeof(peer);
n = recvfrom(sd, buf, sizeof(buf), 0,
(struct sockaddr *)&peer, &peer_len);
if (n == -1) {
perror("recvfrom");
continue;
}
sendto(sd, buf, n, 0, (struct sockaddr *)&peer, peer_len);
}
For a simple request/reply client, sending one datagram and
immediately blocking in recvfrom is fragile: the reply may
be lost, and the client may wait forever. Real UDP protocols need
timeouts and retry rules.
Calling connect on a datagram socket does not create a
TCP-like connection. It stores a default peer address in the kernel.
After that, the program can use send/recv or
write/read, and incoming datagrams from other
peers are normally ignored for that socket.
create a datagram socket with SOCK_DGRAM
sendto sends a datagram; recvfrom receives one
common arguments:
sendto destination has the selected family's address structure
source comments on the history of socklen_t
recvfrom can return the sender's address
choose datagram size with path constraints in mind
naive request/reply sequence can block forever
bound waiting time and decide what to do when it expires
other receive-timeout mechanisms:
example SO_RCVTIMEO = 3.5 seconds
A TCP server creates a listening socket:
int listen(int sockfd, int qlen);
The usual server setup:
socket(AF_INET, SOCK_STREAM, 0)SO_REUSEADDRbindlistenacceptAccept a connection:
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
accept returns a new descriptor for this client
connection. The original listening descriptor remains open for future
clients.
Client side:
int connect(int sockfd, const struct sockaddr *addr, int addrlen);
After connect succeeds on the client and
accept succeeds on the server, both sides use the connected
socket as a byte stream.
Important stream-socket facts:
| Fact | Consequence |
|---|---|
| TCP is a byte stream | Message boundaries are not preserved |
read may return less |
Loop until the needed amount or protocol delimiter is reached |
write may write less |
Loop until all intended bytes are accepted |
read returns 0 |
The peer closed its sending direction |
| One listening socket | Many accepted sockets may exist at the same time |
Closing a connected socket:
int shutdown(int sockfd, int how);
how |
Effect |
|---|---|
SHUT_RD |
Stop receiving |
SHUT_WR |
Finish sending; peer sees end-of-file |
SHUT_RDWR |
Stop both directions |
shutdown affects the socket object. It does not close
the descriptor; still call close later.
stream communication begins by establishing a connection
server has a listening socket and separate connected sockets
server setup: socket -> bind -> listen
listen backlog concerns pending connections awaiting acceptance
choose backlog with workload and system limits in mind
accept obtains the next pending connection
accept address arguments report the peer
accept returns a new connected descriptor, or -1 on error
client setup: socket -> connect
connect takes the remote server endpoint
connected stream supports read and write
UDP connect sets a default peer without a TCP-style handshake
close releases one descriptor reference
last descriptor close initiates socket cleanup
shutdown changes permitted communication directions
shutdown directions:
shutdown affects the socket itself, across all descriptor references
SHUT_WR performs a half-close
SHUT_RD declares that the application will receive no more data
ordinary close can return while kernel still has unsent output
SO_LINGER changes close behavior
SO_LINGER is configured with setsockopt
transport acknowledgment does not prove the remote application processed data
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>
enum {
listen_queue_len = 16,
buf_len = 4096,
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
void set_sigactions(int signum, signalhandler_t handler)
{
int r;
struct sigaction act = { 0 };
act.sa_handler = handler;
r = sigaction(signum, &act, NULL);
if (r == -1)
terminate("sigaction");
}
void handler_sigchld(int s)
{
int pid, status, save_errno;
save_errno = errno;
do {
pid = waitpid(-1, &status, WNOHANG);
} while (pid > 0);
errno = save_errno;
}
static void process_requests(int fd)
{
int fd2, pid, rc;
struct sockaddr_un addr;
socklen_t len;
char buf[buf_len];
while (1) {
len = sizeof(addr);
fd2 = accept(fd, (struct sockaddr *) &addr, &len);
if (fd2 == -1) {
if (errno == EINTR)
continue;
terminate("accept");
}
pid = fork();
if (pid == 0) {
close(fd);
rc = read(fd2, buf, buf_len);
write(1, buf, rc);
close(fd2);
exit(0);
}
close(fd2);
}
}
int main()
{
int fd, res;
struct sockaddr_un addr;
char *file_name;
set_sigactions(SIGCHLD, handler_sigchld);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
file_name = "socket07.t";
strcpy(addr.sun_path, file_name);
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
listen(fd, listen_queue_len);
process_requests(fd);
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
enum {
listen_queue_len = 16
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int fd;
struct sockaddr_un addr;
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket07.t");
connect(fd, (struct sockaddr *) &addr, sizeof(addr));
write(fd, "hello\n", 6);
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>
enum {
listen_queue_len = 16,
datagram_len = 508,
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
void set_sigactions(int signum, signalhandler_t handler)
{
int r;
struct sigaction act = { 0 };
act.sa_handler = handler;
r = sigaction(signum, &act, NULL);
if (r == -1)
terminate("sigaction");
}
void handler_sigchld(int s)
{
int pid, status, save_errno;
save_errno = errno;
do {
pid = waitpid(-1, &status, WNOHANG);
} while (pid > 0);
errno = save_errno;
}
int main()
{
int fd, bytes, res;
struct sockaddr_un addr;
socklen_t len;
char buf[datagram_len];
char *file_name;
set_sigactions(SIGCHLD, handler_sigchld);
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
file_name = "socket08.t";
strcpy(addr.sun_path, file_name);
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
len = sizeof(addr);
bytes = recvfrom(fd, buf, datagram_len, 0,
(struct sockaddr *) &addr, &len);
if (bytes == -1)
terminate("recvfrom");
write(1, buf, bytes);
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
enum {
listen_queue_len = 16,
datagram_len = 508
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int fd, len, bytes;
struct sockaddr_un addr;
char buf[datagram_len];
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket08.t");
strcpy(buf, "hello\n");
len = strlen(buf);
if (len > datagram_len) {
fprintf(stderr, "Too much data trying to send in 1 packet\n");
exit(1);
}
bytes = sendto(fd, buf, len, 0, (struct sockaddr *) &addr, sizeof(addr));
if (bytes == -1)
terminate("sendto");
close(fd);
return 0;
}
CFLAGS=-Wall
all: program-a1 program-b
clean:
-rm -f *.o *~ program-a1 program-b
program-a0: program-a1.o
$(CC) program-a1.o -o $@
program-b0: program-b.o
$(CC) program-b.o -o $@
/* Goal: send large amount of data over TCP to a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctrls and socket options.
Run as 'program-a 1.2.3.4' to connect to 1.2.3.4 port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#ifdef __linux__
#include <linux/sockios.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* in the interest of brevity, this code does not contain a lot of error checking */
void makeSocketLinger(int fd)
{
struct linger ling;
ling.l_onoff=1;
ling.l_linger=30;
setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
}
void depleteSendBuffer(int fd)
{
#ifdef __linux__
int lastOutstanding=-1;
for(;;) {
int outstanding;
ioctl(fd, SIOCOUTQ, &outstanding);
if(outstanding != lastOutstanding)
printf("Outstanding: %d\n", outstanding);
lastOutstanding = outstanding;
if(!outstanding)
break;
usleep(1000);
}
#endif
}
int main(int argc, char** argv)
{
signal(SIGPIPE, SIG_IGN);
int sock=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in remote;
remote.sin_family=AF_INET;
inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &remote.sin_addr);
remote.sin_port = ntohs(9876);
makeSocketLinger(sock);
if(connect(sock, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
perror("Connecting to remote");
exit(1);
}
char buffer[4000];
int n, res;
for(n=0; n < 250 ; ++n) {
res=write(sock, buffer, sizeof(buffer));
if(res != sizeof(buffer)) {
if(res < 0)
perror("writing");
else
fprintf(stderr,"Partial write\n");
exit(1);
}
}
shutdown(sock, SHUT_WR); /* inform remote that we are done */
depleteSendBuffer(sock);
// now wait for the remote to close its socket
for(;;) {
res=read(sock, buffer, sizeof(buffer));
if(res < 0) {
perror("reading");
exit(1);
}
if(!res) {
printf("Correct EOF\n");
break;
}
}
close(sock);
return 0;
}
/* Goal: send large amount of data over TCP to a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctrls and socket options.
Run as 'program-a 1.2.3.4' to connect to 1.2.3.4 port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#ifdef __linux__
#include <linux/sockios.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* in the interest of brevity, this code does not contain a lot of error checking */
int main(int argc, char** argv)
{
signal(SIGPIPE, SIG_IGN);
int sock=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in remote;
remote.sin_family=AF_INET;
inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &remote.sin_addr);
remote.sin_port = ntohs(9876);
if(connect(sock, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
perror("Connecting to remote");
exit(1);
}
char buffer[4000];
int n, res;
for(n=0; n < 250 ; ++n) {
res=write(sock, buffer, sizeof(buffer));
if(res != sizeof(buffer)) {
if(res < 0)
perror("writing");
else
fprintf(stderr,"Partial write\n");
exit(1);
}
}
close(sock);
return 0;
}
/* Goal: send large amount of data over TCP to a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctrls and socket options.
Run as 'program-a 1.2.3.4' to connect to 1.2.3.4 port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#ifdef __linux__
#include <linux/sockios.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* in the interest of brevity, this code does not contain a lot of error checking */
void depleteSendBuffer(int fd)
{
#ifdef __linux__
int lastOutstanding=-1;
for(;;) {
int outstanding;
ioctl(fd, SIOCOUTQ, &outstanding);
if(outstanding != lastOutstanding)
printf("Outstanding: %d\n", outstanding);
lastOutstanding = outstanding;
if(!outstanding)
break;
usleep(1000);
}
#endif
}
int main(int argc, char** argv)
{
signal(SIGPIPE, SIG_IGN);
int sock=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in remote;
remote.sin_family=AF_INET;
inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &remote.sin_addr);
remote.sin_port = ntohs(9876);
if(connect(sock, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
perror("Connecting to remote");
exit(1);
}
char buffer[4000];
int n, res;
for(n=0; n < 250 ; ++n) {
res=write(sock, buffer, sizeof(buffer));
if(res != sizeof(buffer)) {
if(res < 0)
perror("writing");
else
fprintf(stderr,"Partial write\n");
exit(1);
}
}
shutdown(sock, SHUT_WR); /* inform remote that we are done */
depleteSendBuffer(sock);
// now wait for the remote to close its socket
for(;;) {
res=read(sock, buffer, sizeof(buffer));
if(res < 0) {
perror("reading");
exit(1);
}
if(!res) {
printf("Correct EOF\n");
break;
}
}
close(sock);
return 0;
}
/* Goal: receive a non-trivial amount of data over TCP from a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctls and socket options.
Run as 'program-b' and it will listen on port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void setSocketReusable(int fd)
{
int tmp=1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp,sizeof tmp);
}
int main(int argc, char** argv)
{
int sock=socket(AF_INET, SOCK_STREAM, 0);
setSocketReusable(sock);
struct sockaddr_in local;
local.sin_family=AF_INET;
inet_pton(AF_INET, "0.0.0.0", &local.sin_addr);
local.sin_port = ntohs(9876);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0) {
perror("Binding socket");
exit(1);
}
listen(sock, 5);
socklen_t socklen=sizeof(local);
int client=accept(sock, (struct sockaddr*)&local, &socklen);
write(client, "welcome\r\n", 9);
if(client < 0) {
perror("Accepting connection");
exit(1);
}
char buffer[4096];
unsigned int bytesRead=0;
int res;
for(;;) {
res = read(client, buffer, sizeof(buffer));
if(res < 0) {
printf("Read error after %u bytes: %s\n", bytesRead, strerror(errno));
exit(1);
}
if(!res) {
printf("EOF\n");
break;
}
bytesRead += res;
}
printf("%d\n", bytesRead);
return 0;
}
/* Goal: receive a non-trivial amount of data over TCP from a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctls and socket options.
Run as 'program-b' and it will listen on port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void setSocketReusable(int fd)
{
int tmp=1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp,sizeof tmp);
}
int main(int argc, char** argv)
{
int sock=socket(AF_INET, SOCK_STREAM, 0);
setSocketReusable(sock);
struct sockaddr_in local;
local.sin_family=AF_INET;
inet_pton(AF_INET, "0.0.0.0", &local.sin_addr);
local.sin_port = ntohs(9876);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0) {
perror("Binding socket");
exit(1);
}
listen(sock, 5);
socklen_t socklen=sizeof(local);
int client=accept(sock, (struct sockaddr*)&local, &socklen);
write(client, "welcome\r\n", 9);
if(client < 0) {
perror("Accepting connection");
exit(1);
}
char buffer[4096];
unsigned int bytesRead=0;
int res;
for(;;) {
res = read(client, buffer, sizeof(buffer));
if(res < 0) {
printf("Read error after %u bytes: %s\n", bytesRead, strerror(errno));
exit(1);
}
if(!res) {
printf("EOF\n");
break;
}
bytesRead += res;
}
printf("%d\n", bytesRead);
return 0;
}
./program-b &
pid2=$!
./program-a &
pid1=$!
while kill -0 "$pid1" 2>/dev/null && kill -0 "$pid2" 2>/dev/null; do
sleep 0.01
done
if ! kill -0 "$pid1" 2>/dev/null; then
echo "program-a finished first"
else
echo "program-b finished first"
fi
#!/usr/bin/env bash
./program-b &
pid_b=$!
./program-a1 &
pid_a=$!
wait -n -p finished_pid "$pid_a" "$pid_b"
if [[ "$finished_pid" == "$pid_a" ]]; then
echo "A finished first"
elif [[ "$finished_pid" == "$pid_b" ]]; then
echo "B finished first"
fi
wait "$pid_a" "$pid_b" 2>/dev/null
After a TCP server exits, the port may remain unusable for a while
because the kernel keeps old connection state, often in
TIME_WAIT. This prevents delayed packets from an old
connection from confusing a new connection using the same address
pair.
During development this is inconvenient. Set
SO_REUSEADDR before bind:
int opt = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Always check bind errors. If bind fails and
the program continues, later socket calls will produce confusing
behavior.
restarting a TCP server can encounter address-in-use errors
bind may fail while relevant old state remains
SO_REUSEADDR can permit normal server-address reuse
example option setup:
For local communication between related processes,
socketpair creates two already-connected sockets:
int socketpair(int family, int type, int protocol, int sv[2]);
Typical use:
int sv[2];
socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
Compared with pipe, a stream socketpair is
bidirectional. Each end can both read and write.
socketpair creates an already-connected pair for local communication
typical call: socketpair(AF_UNIX, SOCK_STREAM, 0, sv)
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <sys/wait.h>
enum { num_prints = 10, buf_len = 4096 };
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int pid, res, sv[2], i, rc;
char buf[buf_len];
res = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
if (res == -1)
terminate("socketpair");
pid = fork();
if (pid == 0) {
close(sv[0]);
for (i = 0; i < num_prints; i++)
write(sv[1], "hello\n", 6);
close(sv[1]);
exit(0);
}
close(sv[1]);
for (i = 0; i < num_prints; i++) {
rc = read(sv[0], buf, buf_len);
write(1, buf, rc);
}
close(sv[0]);
wait(NULL);
return 0;
}
Network servers often have to wait for many possible events:
The problem is not knowing which blocking call is safe to make next.
Calling accept can block while an existing client is
waiting. Calling read on one client can block while another
client sends data. Calling write can block if the peer or
network cannot accept data fast enough.
A naive loop over nonblocking descriptors avoids blocking, but it becomes active waiting:
int flags;
flags = fcntl(sd, F_GETFL);
fcntl(sd, F_SETFL, flags | O_NONBLOCK);
Active waiting wastes CPU time because the process repeatedly asks every socket whether anything happened. A server that does no useful work should sleep until some event matters.
Etude 6.08 is a server that handles one client at a time: it accepts a connection, writes the date and the client's own address, and closes it. This ordering works only because each session is a single write; a session that has to wait for its client would stall everyone else:
static void process_requests(int fd)
{
int fd2;
struct sockaddr_in addr;
socklen_t len;
while (1) {
len = sizeof(addr);
fd2 = accept(fd, (struct sockaddr *) &addr, &len);
if (fd2 == -1)
terminate("accept");
write_data(fd2, &addr);
close(fd2);
}
}
$ ./daytime 7654 # becomes a daemon and returns
$ nc localhost 7654
Mon Sep 28 12:59:08 2026 - 127.0.0.1:42648
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <sys/wait.h>
enum {
listen_queue_len = 16,
datagram_len = 508,
time_size = 26
};
typedef void (*signalhandler_t)(int);
void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int str2num(const char *str)
{
int n;
char *endptr;
n = strtol(str, &endptr, 10);
if (errno == ERANGE)
terminate("strtol");
if (endptr == str) {
fprintf(stderr, "Incorrect input\n");
exit(1);
}
return n;
}
static void fork_process()
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork");
if (pid > 0)
exit(0);
}
static void launch_daemon()
{
int ret;
close(0);
close(1);
close(2);
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
open("/dev/null", O_WRONLY);
ret = chdir("/");
if (ret == -1)
terminate("chdir");
fork_process();
ret = setsid();
if (ret == -1)
terminate("setsid");
fork_process();
}
static int create_socket(int port)
{
int fd, res, opt;
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
terminate("socket");
opt = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return fd;
}
static void write_data(int fd, struct sockaddr_in *addr)
{
time_t t;
char buf[datagram_len], ip_buf[INET_ADDRSTRLEN], str_time[time_size];
t = time(NULL);
ctime_r(&t, str_time);
str_time[strlen(str_time) - 1] = 0;
inet_ntop(AF_INET, (struct in_addr *) &addr->sin_addr,
ip_buf, INET_ADDRSTRLEN);
sprintf(buf, "%s - %s:%d\n", str_time, ip_buf, ntohs(addr->sin_port));
write(fd, buf, strlen(buf));
}
static void process_requests(int fd)
{
int fd2;
struct sockaddr_in addr;
socklen_t len;
while (1) {
len = sizeof(addr);
fd2 = accept(fd, (struct sockaddr *) &addr, &len);
if (fd2 == -1)
terminate("accept");
write_data(fd2, &addr);
close(fd2);
}
}
int main(int argc, char **argv)
{
int fd;
if (argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
return 1;
}
launch_daemon();
fd = create_socket(str2num(argv[1]));
listen(fd, listen_queue_len);
process_requests(fd);
close(fd);
return 0;
}
a server has several possible sources of work
blocking in read / recv has the same problem
writes can block too
restaurant analogy: one waiter, separate booths, and an entrance
one possible approach: make every socket nonblocking and poll them repeatedly
busy waiting wastes CPU time
an idle server should consume little CPU
first useful solution: a separate worker process for each client
second solution: wait for notification that something needs attention
the following subsections develop worker processes and event-driven operation
A simple design is to dedicate one child process to each accepted client. The parent accepts connections; the child serves one client.
Sketch:
int ls, cls;
int pid;
for (;;) {
cls = accept(ls, NULL, NULL);
if (cls == -1) {
if (errno == EINTR) {
continue;
}
perror("accept");
continue;
}
pid = fork();
if (pid == 0) {
close(ls);
/* serve client through cls */
close(cls);
_exit(0);
}
close(cls);
while (waitpid(-1, NULL, WNOHANG) > 0) {
;
}
}
This is easy to understand and isolates clients from each other. It becomes expensive when there are many short connections or when all clients must share one live state, such as a multiplayer game world.
If children are used, handle SIGCHLD or otherwise reap
finished children. accept may fail with EINTR
when interrupted by a signal.
parent accepts connections; each child serves one connection
setup:
main loop:
reaping only after another accept can leave zombies indefinitely
An event-driven server uses one main loop. It sleeps until one or more descriptors are ready, then performs small pieces of work for those descriptors.
Rules:
| Rule | Reason |
|---|---|
| Keep each event handler short | Other clients must not starve |
| Track per-client state explicitly | The call stack cannot represent all clients |
| Avoid blocking calls inside handlers | One slow client must not stop the server |
| Remember partial reads and writes | TCP has no message boundaries |
This style is more complex than one-process-per-client code, but it scales better for many mostly-idle connections.
Etude 6.12 serves any number of clients in one process, answering
Ok to every line. Each pass of the loop waits in
select for whichever descriptor is ready: the listening
socket means a new client, any other means data from a session:
static void run_server(server_t *s)
{
int i, res;
fd_set readfds;
while (1) {
FD_ZERO(&readfds);
FD_SET(s->fd_listen, &readfds);
for (i = 0; i < s->n; i++)
if (s->fd_connected[i])
FD_SET(i, &readfds);
res = select(s->n, &readfds, NULL, NULL, NULL);
if (res == -1)
terminate("select");
if (FD_ISSET(s->fd_listen, &readfds))
accept_connection(s);
for (i = 0; i < s->n; i++)
if (s->fd_connected[i] && FD_ISSET(i, &readfds))
process_session(s, i);
}
}
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
enum {
max_num_clients = 1024,
buf_size = 508,
listen_qlen = 32
};
const char msg[] = "Ok\n";
typedef struct {
int fd_listen;
int fd_connected[max_num_clients];
int n;
} server_t;
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
static void fork_process()
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork");
if (pid > 0)
exit(0);
}
void launch_daemon()
{
int ret;
close(0);
close(1);
close(2);
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
open("/dev/null", O_WRONLY);
ret = chdir("/");
if (ret == -1)
terminate("chdir");
fork_process();
ret = setsid();
if (ret == -1)
terminate("setsid");
fork_process();
}
static int str2num(const char *str)
{
int n;
char *endptr;
n = strtol(str, &endptr, 10);
if (errno == ERANGE)
terminate("strtol");
if (!*str || *endptr) {
fprintf(stderr, "Cannot convert string to number\n");
exit(1);
}
return n;
}
static void init_server(server_t *s)
{
int i;
for (i = 0; i < max_num_clients; i++)
s->fd_connected[i] = 0;
s->n = 0;
s->fd_listen = 0;
}
static void start_server(server_t *s, int port)
{
int fd, res, opt;
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
terminate("socket");
opt = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
listen(fd, listen_qlen);
s->fd_listen = fd;
s->n = fd + 1;
}
static void accept_connection(server_t *s)
{
int fd;
struct sockaddr_in addr;
socklen_t len;
len = sizeof(addr);
fd = accept(s->fd_listen, (struct sockaddr *) &addr, &len);
if (fd == -1)
terminate("accept");
s->fd_connected[fd] = 1;
if (fd + 1 > s->n)
s->n = fd + 1;
}
static void process_session(server_t *s, int fd)
{
int rc, i;
char buf[buf_size];
rc = read(fd, buf, buf_size);
if (rc <= 0) {
close(fd);
s->fd_connected[fd] = 0;
} else {
for (i = 0; i < rc; i++)
if (buf[i] == '\n')
write(fd, msg, sizeof(msg) - 1);
}
}
static void run_server(server_t *s)
{
int i, res;
fd_set readfds;
while (1) {
FD_ZERO(&readfds);
FD_SET(s->fd_listen, &readfds);
for (i = 0; i < s->n; i++)
if (s->fd_connected[i])
FD_SET(i, &readfds);
res = select(s->n, &readfds, NULL, NULL, NULL);
if (res == -1)
terminate("select");
if (FD_ISSET(s->fd_listen, &readfds))
accept_connection(s);
for (i = 0; i < s->n; i++)
if (s->fd_connected[i] && FD_ISSET(i, &readfds))
process_session(s, i);
}
}
int main(int argc, char **argv)
{
int port;
server_t s;
if (argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
return 1;
}
launch_daemon();
init_server(&s);
port = str2num(argv[1]);
start_server(&s, port);
run_server(&s);
close(s.fd_listen);
return 0;
}
one process per client is not always convenient
alternative: one process handles many event sources without busy waiting
event-driven program:
each iteration has two phases:
event handlers must return promptly
do not issue an operation that can block indefinitely inside a handler
sequential application logic must become resumable
select waits until at least one descriptor is ready, a
timeout expires, or a signal interrupts the wait:
int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
struct timeval *timeout);
Descriptor sets are manipulated with macros:
FD_ZERO(&set);
FD_SET(fd, &set);
FD_CLR(fd, &set);
FD_ISSET(fd, &set);
n is one more than the largest descriptor number being
watched.
The three descriptor sets mean:
| Set | Ready means |
|---|---|
readfds |
Reading can be attempted without blocking |
writefds |
Writing can be attempted without blocking |
exceptfds |
Exceptional conditions; rarely used in simple socket programs |
For a listening socket, readability means an incoming connection can be accepted. For a datagram socket, readability means a datagram can be read. For a stream socket, readability can mean data arrived, end-of-file arrived, or an error must be observed.
select overwrites the sets. Rebuild them on every
iteration:
for (;;) {
fd_set readfds;
int maxfd = listen_fd;
int res;
FD_ZERO(&readfds);
FD_SET(listen_fd, &readfds);
/* add client descriptors and update maxfd */
res = select(maxfd + 1, &readfds, NULL, NULL, NULL);
if (res == -1) {
if (errno == EINTR) {
continue;
}
perror("select");
break;
}
if (FD_ISSET(listen_fd, &readfds)) {
/* accept new connection */
}
/* check clients */
}
Timeouts use struct timeval:
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
Some systems modify the timeout value. For portable code, recreate it
before each select call.
Write readiness should be watched only for descriptors that actually
have queued output. Most sockets are writable most of the time; watching
every socket for writing can make select return immediately
in a busy loop.
efficient event waiting needs kernel support
wait for any event from a set:
I/O multiplexing: readiness selects which I/O operation to attempt next
Unix readiness interfaces include select and poll
select(n, readfds, writefds, exfds, timeout)
fd_set represents a descriptor set
fd_set has a descriptor-number limit
FD_SETSIZE and the process's descriptor limit are different limits
timeout uses struct timeval
select may modify the timeout structure
unused set pointers may be NULL
select return values:
input sets are overwritten with the corresponding ready subsets
exfds is often unused in simple socket applications
readability means a read can produce a result without waiting
readfds also supports sockets used through other operations
writability does not promise space for an arbitrarily large write
robust output uses a nonblocking socket and a per-client output buffer
watch for writability only when there is output to send
server-loop outline:
two phases remain distinct in that outline
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#ifndef INBUFSIZE
#define INBUFSIZE 1024
#endif
#ifndef LISTEN_QLEN
#define LISTEN_QLEN 32
#endif
#ifndef INIT_SESS_ARR_SIZE
#define INIT_SESS_ARR_SIZE 32
#endif
enum fsm_states {
fsm_start, fsm_name = fsm_start, fsm_age, fsm_town, fsm_band,
fsm_finish, fsm_error
};
struct session {
int fd;
unsigned long from_ip;
unsigned short from_port;
char buf[INBUFSIZE];
int buf_used;
enum fsm_states state;
char *name, *town, *band;
int age;
};
static void session_send_string(struct session *sess, const char *str)
{
write(sess->fd, str, strlen(str));
}
static struct session *make_new_session(int fd, struct sockaddr_in *from)
{
struct session *sess = malloc(sizeof(*sess));
sess->fd = fd;
sess->from_ip = ntohl(from->sin_addr.s_addr);
sess->from_port = ntohs(from->sin_port);
sess->buf_used = 0;
sess->state = fsm_start;
sess->name = NULL;
sess->town = NULL;
sess->band = NULL;
sess->age = -1;
session_send_string(sess, "What is your name?\n");
return sess;
}
static void session_cleanup(struct session *sess)
{
if(sess->name)
free(sess->name);
if(sess->town)
free(sess->town);
if(sess->band)
free(sess->band);
}
static void session_handle_age(struct session *sess, const char *line)
{
char *err;
int age;
age = strtol(line, &err, 10);
if(!*line || *err || age < 0 || age > 150) {
session_send_string(sess, "No, this can't be your age!\n");
session_send_string(sess, "Please try again!\n");
session_send_string(sess, "How old are you?\n");
} else {
sess->age = age;
session_send_string(sess, "What city/town are you from?\n");
sess->state = fsm_town;
}
}
/* ownership over the 'line' is transferred here */
static void session_fsm_step(struct session *sess, char *line)
{
switch(sess->state) {
case fsm_name:
sess->name = line;
session_send_string(sess, "How old are you?\n");
sess->state = fsm_age;
break;
case fsm_age:
session_handle_age(sess, line);
free(line); /* because we still own it... */
break;
case fsm_town:
sess->town = line;
session_send_string(sess, "What is your favorite band?\n");
sess->state = fsm_band;
break;
case fsm_band:
sess->band = line;
session_send_string(sess, "Thank you, bye!\n");
sess->state = fsm_finish;
break;
case fsm_finish:
case fsm_error:
free(line); /* this should never happen */
}
}
static void session_check_lf(struct session *sess)
{
int pos = -1;
int i;
char *line;
for(i = 0; i < sess->buf_used; i++) {
if(sess->buf[i] == '\n') {
pos = i;
break;
}
}
if(pos == -1)
return;
line = malloc(pos+1);
memcpy(line, sess->buf, pos);
line[pos] = 0;
sess->buf_used -= (pos+1);
memmove(sess->buf, sess->buf+pos+1, sess->buf_used);
if(line[pos-1] == '\r')
line[pos-1] = 0;
session_fsm_step(sess, line); /* we transfer ownership! */
}
static int session_do_read(struct session *sess)
{
int rc, bufp = sess->buf_used;
rc = read(sess->fd, sess->buf + bufp, INBUFSIZE - bufp);
if(rc <= 0) {
sess->state = fsm_error;
return 0; /* this means "don't continue" for the caller */
}
sess->buf_used += rc;
session_check_lf(sess);
if(sess->buf_used >= INBUFSIZE) {
/* we can't read further, no room in the buffer, no whole line yet */
session_send_string(sess, "Line too long! Good bye...\n");
sess->state = fsm_error;
return 0;
}
if(sess->state == fsm_finish)
return 0;
return 1;
}
static void session_commit(struct session *sess, FILE *f)
{
unsigned int ip = sess->from_ip;
fprintf(f, "From %d.%d.%d.%d:%d\n"
"Name: %s\nAge: %d\nTown: %s\nBand: %s\n\n",
(ip>>24 & 0xff), (ip>>16 & 0xff), (ip>>8 & 0xff), (ip & 0xff),
sess->from_port,
sess->name, sess->age, sess->town, sess->band);
fflush(f);
}
/* =========== server =========== */
struct server_str {
int ls;
FILE *res;
struct session **sess_array;
int sess_array_size;
};
static int server_init(struct server_str *serv, int port, const char *fname)
{
int sock, i, opt, res;
struct sockaddr_in addr;
FILE *f;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
perror("socket");
return 0;
}
opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
res = bind(sock, (struct sockaddr*) &addr, sizeof(addr));
if(res == -1) {
perror("bind");
return 0;
}
listen(sock, LISTEN_QLEN);
serv->ls = sock;
f = fopen(fname, "wb");
if(!f) {
perror(fname);
close(sock);
return 0;
}
serv->res = f;
serv->sess_array = malloc(sizeof(*serv->sess_array) * INIT_SESS_ARR_SIZE);
serv->sess_array_size = INIT_SESS_ARR_SIZE;
for(i = 0; i < INIT_SESS_ARR_SIZE; i++)
serv->sess_array[i] = NULL;
return 1;
}
static void server_accept_client(struct server_str *serv)
{
int sd, i;
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
sd = accept(serv->ls, (struct sockaddr*) &addr, &len);
if(sd == -1) {
perror("accept");
return;
}
if(sd >= serv->sess_array_size) { /* need to resize */
int newlen = serv->sess_array_size;
while(sd >= newlen)
newlen += INIT_SESS_ARR_SIZE;
serv->sess_array =
realloc(serv->sess_array, newlen * sizeof(struct session*));
for(i = serv->sess_array_size; i < newlen; i++)
serv->sess_array[i] = NULL;
serv->sess_array_size = newlen;
}
serv->sess_array[sd] = make_new_session(sd, &addr);
}
static void server_remove_session(struct server_str *serv, int sd)
{
close(sd);
serv->sess_array[sd]->fd = -1;
session_cleanup(serv->sess_array[sd]);
free(serv->sess_array[sd]);
serv->sess_array[sd] = NULL;
}
static void server_close_session(struct server_str *serv, int sd)
{
if(serv->sess_array[sd]->state == fsm_finish)
session_commit(serv->sess_array[sd], serv->res);
server_remove_session(serv, sd);
}
static int server_go(struct server_str *serv)
{
fd_set readfds;
int i, sr, ssr, maxfd;
for(;;) { /* ========= THE APPLICATION MAIN LOOP ========= */
FD_ZERO(&readfds); /* ====== GET THE EVENT ====== */
FD_SET(serv->ls, &readfds);
maxfd = serv->ls;
for(i = 0; i < serv->sess_array_size; i++) {
if(serv->sess_array[i]) {
FD_SET(i, &readfds);
if(i > maxfd)
maxfd = i;
}
}
sr = select(maxfd+1, &readfds, NULL, NULL, NULL);
if(sr == -1) {
perror("select");
return 0;
}
if(FD_ISSET(serv->ls, &readfds))
server_accept_client(serv);
for(i = 0; i < serv->sess_array_size; i++) {
if(serv->sess_array[i] && FD_ISSET(i, &readfds)) {
ssr = session_do_read(serv->sess_array[i]);
if(!ssr)
server_close_session(serv, i);
}
}
}
return 1;
}
int main(int argc, const char * const *argv)
{
struct server_str server;
long port;
char *endptr;
int res;
if(argc != 3) {
fprintf(stderr, "Usage: serv <port> <log_file_name>\n");
return 1;
}
port = strtol(argv[1], &endptr, 10);
if(!*argv[1] || *endptr) {
fprintf(stderr, "Invalid port number\n");
return 2;
}
if(!server_init(&server, port, argv[2]))
return 3;
res = server_go(&server);
return res ? 0 : 4;
}
Each client session must be represented by explicit state:
| State | What the server waits for |
|---|---|
| Reading request | Socket readable |
| Processing | No descriptor readiness may be needed |
| Writing response | Socket writable while unsent bytes remain |
| Closing | Flush or close resources |
The state object usually stores:
When an event arrives, the handler advances the session state a little. If more work remains, the next loop iteration will continue it when the needed event is available.
In the card-game server written as the last etudes of this chapter, each connected player is in one of these states:
enum player_state {
connecting,
registering_deciding,
registering,
entering,
chatting,
waiting,
attacking_first,
attacking,
defending,
finished_attacking,
finished_defending
};
Every complete line from a player is handled according to the player's state, and the handlers move the player to the next one:
int respond_to_line(server_t *s, player_t *p, const char *line)
{
int stop, found;
switch (p->state) {
case connecting:
check_user(s, p, line);
break;
case registering_deciding:
want_to_register(p, line);
break;
case registering:
stop = register_user(&s->users, p->name, line);
if (stop)
return 1;
chatting_state(p);
break;
case entering:
found = login_user(s, p, line);
if (!found) {
write_str(p->fd, "wrong password, try again: ");
break;
}
write_user_role(p);
chatting_state(p);
break;
case chatting:
connecting_to_game(s, p, line);
break;
default:
respond_in_game(s, p, line);
}
return 0;
}
an event-driven interaction cannot rely on a blocking sequence of statements
read / recv may return only part of one client request
each client needs its own accumulation buffer
application protocols also contain sequences of separate exchanges
example questionnaire asks, in order:
ordinary Pascal version alternates write(question) with readln(answer)
the same sequential dialogue can use socket write and repeated reads
one blocking dialogue is unsuitable for a shared event loop
on each client's readable event:
session state records the current stage of communication
finite-state machine (FSM):
questionnaire state diagram:
transitions can have both a condition and associated actions
use a distinct error state for a session that cannot continue
more complex protocols can branch according to previous answers
implement states as stored values
state information can include several variables
FSM reacts to events supplied by the surrounding program
example struct session contains:
make_new_session(fd) initializes a newly accepted connection
session_send_string isolates outgoing text handling
that helper is deliberately simplified for this small demonstration
session_fsm_step(sess, line) receives ownership of a complete allocated line
ownership avoids copying saved text unnecessarily
switch(state) selects the action for the current FSM state
age helper:
main loop should use a session interface instead of manipulating the FSM
session_do_read:
session_check_lf connects byte-stream handling with the FSM
for pipelined input, process additional complete buffered lines promptly
tcp_questn.c in the book's examples contains the complete questionnaire server
explicit states replace information previously carried by control flow
An event-driven server cannot rely on a simple sequence of blocking calls such as:
read request -> compute response -> write response
connect on a TCP socket can block while the connection
is being established. In an event-driven program, make the socket
nonblocking first:
int flags;
int res;
flags = fcntl(sd, F_GETFL);
fcntl(sd, F_SETFL, flags | O_NONBLOCK);
res = connect(sd, (struct sockaddr *)&addr, sizeof(addr));
Possible results:
| Result | Meaning |
|---|---|
0 |
Connected immediately |
-1, errno == EINPROGRESS |
Connection attempt started; wait for result |
Other -1 |
Immediate failure |
After EINPROGRESS, wait for the socket to become
writable with select. Then read the final connection status
with getsockopt:
int err;
socklen_t len = sizeof(err);
getsockopt(sd, SOL_SOCKET, SO_ERROR, &err, &len);
if (err == 0) {
/* connected */
} else {
/* connection failed; err is the error code */
}
a program can act as both server and client
ordinary connect can block until establishment succeeds or fails
make the socket nonblocking before connect
possible outcomes:
a pending connect uses writable readiness
check the outcome with getsockopt
after successful getsockopt:
Signals can be treated as events in a main loop, but there is a race:
selectThe signal was delivered, but the program may not react until some
unrelated event wakes select.
pselect solves the same class of race that
sigsuspend solves for signal waiting. It atomically changes
the signal mask for the duration of the wait.
int pselect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
const struct timespec *timeout, const sigset_t *sigmask);
Unlike select, the timeout uses
struct timespec:
| Field | Meaning |
|---|---|
tv_sec |
Seconds |
tv_nsec |
Nanoseconds, 0..999999999 |
The usual pattern:
volatile int usr1_caught;
static void usr1_handler(int signo)
{
usr1_caught = 1;
}
sigset_t block_usr1, original_mask;
sigemptyset(&block_usr1);
sigaddset(&block_usr1, SIGUSR1);
sigprocmask(SIG_BLOCK, &block_usr1, &original_mask);
signal(SIGUSR1, usr1_handler);
for (;;) {
fd_set readfds;
FD_ZERO(&readfds);
/* fill descriptor sets */
pselect(maxfd + 1, &readfds, NULL, NULL, NULL, &original_mask);
if (usr1_caught) {
usr1_caught = 0;
/* handle SIGUSR1 as a normal event */
}
/* handle descriptor events */
}
The key idea is that the signal is blocked during ordinary code and
unblocked only while the process is inside pselect. If it
arrives, it wakes the wait and the main loop can handle it immediately
in normal program context.
For many practical programs, a short select timeout is
enough. Still, the pselect pattern is the correct tool when
signal responsiveness must not depend on unrelated descriptor
events.
signal notifications can become events in a select-based program
a caught signal interrupts select with -1 / EINTR
minimal signal handler records that work is pending
perform substantive work in an ordinary main-loop function
example sequence: preparation A -> select -> code B -> process signal flag -> C
signal during A or C creates a lost-wakeup problem
visible effect: a control request appears to have been ignored
first attempted fix: process the flag immediately before select
a signal can still arrive between the final check and select
this is the same problem as checking a flag before pause
pselect adds atomic signal-mask replacement to select-style waiting
for this pattern, sigmask temporarily permits the awaited signal
SIGUSR1 event-loop pattern:
ordinary select can be sufficient when bounded notification delay is acceptable
Previous: Operating Systems Reading map Next: Parallel Programming
Comments