Networks and Protocols

Reading map

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

Computer Networks

A 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.

Detailed notes - 6.1: Computer networks

1

computer network: connected computers able to exchange data

  • at least two participants
  • historical store-and-forward exchanges even used removable media
  • this chapter considers networks with actual communication links

Network Connections

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.

Detailed notes - 6.1.1: Networks and network connections

1

communication networks can use fixed connections

  • endpoints remain connected according to a fixed wiring scheme
  • changes require manual reconnection
  • examples: public-address systems and field telephones with dedicated wires

2

circuit switching:

  • endpoints attach to switches forming a switching network
  • control commands establish and release connections
  • traditional telephone networks illustrate this model

3

packet switching:

  • digital information is divided into packets
  • each packet contains destination information
  • network forwards each packet toward its recipient
  • one physical link carries packets for many different conversations

4

chapter's scope: packet-switched computer networks

  • other specialized arrangements exist
  • data travels in small addressed units
  • network forwarding does not itself guarantee successful delivery

5

physical media vary widely

  • electrical cables, radio, optical fiber, infrared, directed light
  • differences include modulation, synchronization, cable type/length, wire count
  • wired versus wireless alone is an incomplete classification

6

applications can often ignore the physical transmission technology

  • Internet access can work through mobile radio, Wi-Fi, Ethernet, DSL, ...
  • higher layers provide a common interface

7

physical access still affects security assumptions

  • radio can extend beyond the intended room or building
  • a shared password is known to multiple people and can spread
  • control access to services such as printers rather than trusting proximity

8

physical topology and logical communication topology are different

  • bus, star, ring, mesh describe different arrangements
  • a physically star-shaped network can behave like a shared bus
  • topology labels alone do not explain application-visible behavior

9

historical Ethernet used coaxial cable

  • central conductor plus surrounding insulated shield/conductor
  • shield reduces interference and radiation
  • other equipment also uses coaxial cables

10

coaxial Ethernet bus:

  • interfaces connected in parallel with T-connectors
  • example speed: 10 Mbit/s
  • simultaneous transmissions collide
  • heavier traffic causes more collisions and lost useful capacity

11

bus cable required correct termination at both ends

  • 50-ohm terminators suppress reflected signals
  • breaks or disconnected connectors can disrupt the whole segment
  • cable passing every workstation makes accidental damage hard to avoid

12

historical twisted-pair Ethernet replaced the coaxial bus

  • twisting helps reject interference
  • discussed 10/100-Mbit arrangement uses separate transmit/receive pairs
  • crossover wiring can connect two interfaces directly
  • a hub connects multiple machines, one cable per port
  • hub repeats incoming signals onto the other ports

13

switches replaced hubs

  • forward known unicast traffic toward its destination port
  • independent pairs of hosts can communicate without sharing one collision domain
  • broadcast and unknown-destination traffic still require wider forwarding

14

switch maintains address-to-port information

  • inspect each frame's destination
  • one port may lead to several hosts through another switch
  • managed switches also expose configuration/monitoring interfaces
  • VLANs divide ports into separate logical networks

15

manufacturing made simple switches inexpensive

  • enclosure, connectors, power supply, and board are needed for hubs too
  • reduced electronics cost removed the main economic reason to use hubs

16

historically, hubs and especially switches were expensive

  • coaxial networks needed neither
  • lower equipment cost prolonged their use despite maintenance problems

17

coaxial bus -> twisted-pair hub:

  • physical topology changes from bus to star
  • logical behavior remains shared broadcast delivery
  • every connected participant still receives the transmitted signal

18

network cards sometimes supported both coax and twisted pair

  • replacing cabling/hub and selecting the other connector could preserve software setup
  • applications did not need to know that the physical medium changed

19

for programming, classify networks by properties visible to programs

  • physical wiring alone often does not determine the interface they use

20

TCP/IP hides many differences between local and remote communication

  • peer may be across the world, next door, or on the same computer
  • latency and other performance properties can still differ

21

network boundaries can be administrative as well as technical

  • connected networks can form parts of larger networks
  • one administration/security policy can define a network boundary
  • outside peers cannot be trusted merely because they are reachable
  • internal peers also require appropriate checks

22

one logical link can serve several computers

  • Ethernet is a multipoint example
  • participants communicate directly at the link layer
  • intervening hubs/switches are normally transparent to endpoint software

23

point-to-point link connects exactly two endpoints

  • abbreviated PtP
  • can use Ethernet or technology inherently limited to two participants
  • useful for links between networks or to an access provider

24

multipoint links need a way to select the next recipient on the link

  • point-to-point link has only one possible peer
  • link-layer identifiers differ from IP addresses used above them
  • address resolution connects the two kinds of address

25

networking does not require a dedicated network card

  • serial ports and modems historically carried Internet traffic
  • null-modem cable connects nearby serial ports
  • USB, parallel ports, and even SCSI can also transport network data
  • technologies differ in speed and hardware requirements

26

network hardware need not be a separate expansion card

  • Ethernet/Wi-Fi may be built into the motherboard
  • USB adapters are another packaging option

27

network interface: the connection point used to exchange data with other computers

  • term avoids assuming any particular physical card or connector

28

interface can also be a software abstraction

  • virtual interfaces represent tunnels and VPNs
  • VLAN trunking can present several logical interfaces through one physical port
  • each logical interface can participate in its own link/network

Gateways and Routing

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.

Detailed notes - 6.1.2: Gateways and routing

1

one large link has scaling limits

  • link/switch failures can divide connectivity
  • inter-switch links can become bottlenecks
  • broadcasts impose work on all members
  • forwarding loops must be prevented or controlled; redundant physical links need suitable protocols

2

large shared networks also complicate administration and isolation

  • many participants can reach one another directly
  • separating organizations makes security policy easier to enforce

3

one computer can have several network interfaces

  • can participate in several links simultaneously
  • Ethernet and Wi-Fi on one laptop are a familiar example
  • choosing one preferred interface is a policy, not an inherent hardware limit

4

router/gateway forwards packets between networks

  • requires connectivity to those networks and forwarding configuration
  • GW commonly abbreviates gateway

5

home Internet router is also a computer

  • often combines routing, Ethernet switching, and Wi-Fi access
  • runs firmware/OS, sometimes Linux

6

gateway is a transfer point between links

  • routes tell hosts where to send nonlocal packets
  • gateway can filter, limit, log, or translate traffic
  • packets may cross several successive gateways
  • route describes how forwarding carries them toward the destination

7

example: two separate home LANs

  • first: Anna, Boris, Vera
  • second: Gennady, Dmitry, Elena, Zhanna

8

residents want communication between the LANs

  • games, file access, and voice/video communication
  • a link between only Boris and Dmitry is useful to others if they forward traffic

9

joining switches could make one larger LAN

  • duplicate addresses would need resolving
  • physical separation and cable constraints may make this inconvenient
  • residents may also want separate access policies

10

Boris and Dmitry establish a radio link and act as gateways

  • Boris forwards traffic for the second LAN to Dmitry
  • Dmitry forwards traffic for the first LAN to Boris

11

configure other hosts' routes toward the relevant gateway

  • Anna/Vera use Boris to reach the other LAN
  • Gennady/Zhanna use Dmitry
  • Dmitry can filter incoming traffic addressed to Elena
  • local communication within Elena's LAN remains possible

12

add an Internet router to the first LAN

  • local destinations: send directly
  • second LAN: send through Boris
  • all other destinations: send through the provider router
  • last rule is the default route/default gateway

13

extend Internet access to the second LAN

  • Dmitry's default gateway: Boris
  • second-LAN hosts' default gateway: Dmitry
  • redundant more-specific routes using the same next hop can be removed
  • Elena's filter must allow desired replies while blocking unwanted sources

14

possible extensions:

  • second Internet connection and failover routing
  • dedicated gateways instead of personal computers that must stay switched on
  • later sections explain concrete IP routes and address translation
A default route matches every IPv4 destination; a more specific matching route takes priority.
The longest matching prefix selects the route. Open full size - Editable SVG

Network Protocols

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.

Protocols and the OSI Model

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
Detailed notes - 6.2.1: Protocols and the OSI model

1

protocol: agreements participants follow to understand one another

  • several protocols operate together at different levels
  • example stack: physical signaling, TCP transport, HTTP application exchange

2

protocol specification tells implementers how to interoperate

  • describes formats, meanings, rules, and required behavior
  • software/hardware implements these agreements
  • protocol is distinct from one particular implementation

3

OSI = Open Systems Interconnection; seven-layer reference model

  • physical: signals, transmission medium, electrical/optical/radio characteristics
  • data link: frames and communication over one link
  • network: addressing and forwarding between networks
  • transport: communication between endpoints; may provide ordering/reliability
  • session: organization of a conversation
  • presentation: representation/encoding of exchanged data
  • application: rules for the actual service

4

mnemonic from top to bottom: All People Seem To Need Data Processing

  • Application, Presentation, Session, Transport, Network, Data link, Physical
  • OSI is useful as a conceptual model
  • practical Internet protocols need not form seven separate implementation layers

5

author contrasts committee-designed layering with TCP/IP's practical development

  • treat this as the author's commentary
  • central technical point: working protocol stacks need not mirror the reference model
An IP packet crosses different links; each hop uses the frame format appropriate to that link.
Each lower layer carries the unit above it. Open full size - Editable SVG

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.

Detailed notes - 6.2.2: Physical and data-link protocols

1

physical protocol depends on the actual connection

  • 100BASE-TX is a twisted-pair Ethernet example
  • specifies signaling and medium requirements
  • Ethernet specifications also define framing and link-layer addresses
  • a technology's specifications can span more than one conceptual layer

2

Wi-Fi uses the IEEE 802.11 family

  • shared radio medium requires coordination between transmitters
  • channels, bands, and permitted operation vary by standard and region
  • includes physical signaling and medium-access/framing rules

3

cellular access adds its own radio and network protocols

  • book uses GSM/GPRS as examples
  • cellular specifications cover several layers, not just physical transmission

4

RS-232 is a simpler physical-interface example

  • can connect serial ports with a null-modem cable
  • low data rate limits its usefulness for ordinary networking

5

Ethernet/Wi-Fi interfaces use link-layer MAC addresses

  • common MAC address length: six bytes
  • usually displayed as hexadecimal byte pairs, e.g. 00:1F:C6:65:42:48
  • manufacturer-assigned addresses commonly combine an assigned prefix and device-specific part

6

manufacturer address allocations do not all use the same prefix length

  • allocation structure is separate from how applications use IP addresses

7

effective MAC address can differ from the factory address

  • OS/driver can configure a locally chosen address
  • randomization can reduce tracking of mobile Wi-Fi devices
  • MAC address should not be treated as an unchangeable identity

8

ARP resolves an IPv4 next-hop address to a link-layer address

  • sender needs the recipient's MAC address on a multipoint link
  • broadcasts a request asking which interface owns the IP address
  • owner replies with its MAC address
  • sender caches the association for later packets
  • remote destinations are reached using the gateway's local MAC address

9

point-to-point links do not need ARP to choose among several peers

  • PPP is a common link protocol for such connections
  • defines framing and integrity checks
  • can negotiate link settings, check liveness, and authenticate peers

IP

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
Detailed notes - 6.2.3: IP

1

IP provides network-layer packets, addresses, and forwarding

  • higher protocols put their data inside IP packets
  • ICMP also belongs to network-layer operation although carried inside IP
  • ICMP reports delivery problems and other control information
  • conceptual layers do not require one protocol per layer

2

IP supports interconnection of heterogeneous networks

  • different underlying links can carry the same IP packets
  • several paths can provide resilience when links fail
  • book traces development through ARPANET and the 1983 TCP/IP transition

3

Internet consists of networks under many separate administrations

  • no single operator owns all links, hosts, or local networks
  • common protocols let independently built networks cooperate

4

individual links and operators can disappear or change

  • overall resilience must not depend on every component being reliable

5

alternative routes can preserve communication after failures

  • routing must detect changes and find a usable path
  • recovery is not an unconditional or instantaneous guarantee

6

network host: a computer/end system participating in a network

  • addresses identify reachable endpoints/interfaces
  • book distinguishes globally reachable hosts from machines hidden behind NAT
  • NAT/firewall restrictions affect reachability, not whether a machine is technically a host

7

IPv4 address: 32 bits, commonly written as four decimal octets

  • example: 192.168.215.17
  • each octet is from 0 to 255
  • network byte order is big-endian: most significant byte first

8

routing needs to describe sets of destinations compactly

  • one route often serves many addresses in the same network
  • listing every host separately would be impractical

9

prefix/subnet groups addresses sharing their first N bits

  • remaining 32 - N bits vary
  • address count = 2^(32 - N)
  • network address sets all variable bits to zero
  • /29: 8 addresses; /24: 256; /22: 1024

10

CIDR notation: network-address/prefix-length

  • 203.0.113.32/28 contains 16 addresses
  • range: 203.0.113.32 through 203.0.113.47
  • last four bits vary

11

ordinary IPv4 broadcast subnets reserve boundary addresses

  • all-zero host part: subnet identifier
  • all-one host part: directed broadcast
  • special cases such as /31 point-to-point links have different rules
  • an address prefix used only for route aggregation is not itself a physical broadcast subnet

12

/32 prefix selects exactly one IPv4 address

  • 203.0.113.41/32 is a host route

13

one address belongs to nested prefixes of every length

  • 198.51.100.115 belongs to 198.51.100.112/28
  • also to 198.51.100.0/24 and 198.51.0.0/16
  • longer prefix -> smaller, more specific set

14

0.0.0.0/0 includes the entire IPv4 address space

  • no fixed prefix bits
  • useful for a default route

15

assign contiguous prefixes to simplify routing

  • router normally has an address in each directly connected network
  • addresses are associated with interfaces, not one immutable address per computer
  • an interface can also have more than one address

16

some IPv4 ranges have special meanings

  • 127.0.0.0/8: loopback; 127.0.0.1 is the common local-host address
  • 0.0.0.0 has special unspecified/default uses depending on context
  • other reserved ranges are not ordinary public unicast space
  • exact assignments and permitted uses must not be inferred solely from this historical list

17

224.0.0.0/4 is IPv4 multicast address space

  • address identifies a group of receivers
  • one source can distribute the same information to many recipients

18

multicast forwarding builds distribution paths

  • receivers announce group membership to local routers using IGMP
  • multicast routing protocols connect interested networks
  • routers replicate packets only where paths branch
  • -> potentially fewer copies over shared links

19

multicast also supports local control/routing protocols

  • end-to-end Internet multicast requires support along the path
  • local group membership alone does not ensure global multicast delivery

20

private IPv4 ranges:

  • 10.0.0.0/8
  • 172.16.0.0/12
  • 192.168.0.0/16
  • can be reused in independent private networks
  • not globally routed as public addresses
  • NAT can provide outgoing Internet access

21

example LAN addressing:

  • Boris's LAN: 192.168.12.0/24
  • Boris .1; Anna .2; Vera .3
  • Dmitry's LAN: 192.168.13.0/24
  • Dmitry .1; Gennady .2; Elena .3; Zhanna .4
  • reserve .0 for subnet and .255 for broadcast in each /24

22

separate radio link gets a separate subnet

  • 192.168.14.0/30
  • Boris: 192.168.14.1; Dmitry: 192.168.14.2
  • .0 network; .3 broadcast in this illustrative arrangement

23

Internet router's inside address: 192.168.12.100

  • default gateway for hosts on Boris's LAN
  • hosts on Dmitry's LAN instead use local gateway 192.168.13.1

24

two routing forms:

  • destination prefix -> directly connected interface
  • destination prefix -> next-hop gateway IP
  • multipoint-link direct routes normally identify on-link destinations
  • point-to-point link already has an unambiguous peer
  • gateway itself must be reachable

25

example interface names: eth0 for LAN, wlan0 for radio link

  • actual interface names depend on system configuration
  • Gennady/Elena/Zhanna: 192.168.13.0/24 -> eth0 0.0.0.0/0 -> 192.168.13.1

26

Anna/Vera need two different gateways

  • 192.168.12.0/24 -> eth0
  • 192.168.13.0/24 -> 192.168.12.1
  • 0.0.0.0/0 -> 192.168.12.100

27

Boris connects two links

  • 192.168.12.0/24 -> eth0
  • 192.168.14.0/30 -> wlan0
  • 192.168.13.0/24 -> 192.168.14.2
  • 0.0.0.0/0 -> 192.168.12.100

28

Dmitry's routes:

  • 192.168.13.0/24 -> eth0
  • 192.168.14.0/30 -> wlan0
  • 0.0.0.0/0 -> 192.168.14.1

29

Internet router has an inside Ethernet interface and illustrative point-to-point wan0

  • 192.168.12.0/24 -> eth0
  • 192.168.13.0/24 -> 192.168.12.1
  • 0.0.0.0/0 -> wan0
  • external example address: 198.51.100.115
  • that address block is reserved for documentation, not a real assignment

30

routing alone does not make private source addresses globally usable

  • remote networks cannot route replies to independently reused private addresses

31

NAT translates private traffic using the router's external address

  • example internal aggregate: 192.168.12.0/22
  • outgoing packet's source is translated to the external address
  • reply is translated back and forwarded to the internal destination

32

remote peer normally sees the NAT's external address

  • ordinary outgoing mappings allow replies
  • unsolicited incoming connections need suitable mappings/forwarding and policy

33

many-to-one NAT must distinguish simultaneous exchanges

  • track addresses, transport ports, protocol, and mapping state
  • transport headers may also need translation
  • protocols carrying addresses/ports in application data can need extra handling
  • FTP's separate data connection illustrates such complications

34

radio-link subnet can also be advertised to ordinary hosts

  • Anna/Vera can add 192.168.14.0/30 -> 192.168.12.1

35

routers can then be reached through their radio-interface addresses too

  • alternative: a true point-to-point link can use unnumbered routing
  • this relies on actual link semantics; Wi-Fi alone is not automatically a point-to-point interface

36

illustrative unnumbered point-to-point route arrangement:

  • Boris: second LAN -> connecting interface; default -> Internet router
  • Dmitry: own LAN -> eth0; default -> connecting interface
  • removes the separate transit-prefix routes

37

longest-prefix match chooses the most specific matching route

  • /24 beats /22; /22 beats /0
  • Anna/Vera can aggregate neighboring ranges: 192.168.12.0/24 -> eth0 192.168.12.0/22 -> 192.168.12.1 0.0.0.0/0 -> 192.168.12.100

38

more-specific local route overrides the broader aggregate

  • .12.0/24 goes directly through eth0
  • other destinations covered by .12.0/22 go through Boris

39

address conservation matters when the available allocation is small

  • particularly for public IPv4 blocks
  • private allocations can also be constrained by a larger organization's plan

40

compact example requirements:

  • each LAN needs at least /29 if network/broadcast addresses are reserved
  • transit link needs /30
  • 8 + 8 + 4 = 20 addresses -> covering block must be at least /27 (32)
  • use spare space to enlarge Dmitry's LAN to /28 (16 addresses)

41

choose aggregate 192.168.45.64/27: .64 through .95

  • Boris's LAN: .64/29
  • Boris .65; Anna .66; Vera .67; Internet router .70
  • .71 broadcast; .68/.69 spare

42

Dmitry's LAN: 192.168.45.80/28

  • Dmitry .81; Gennady .82; Elena .83; Zhanna .84
  • .95 broadcast; .85-.94 spare
  • prefix boundaries require a correctly aligned block

43

transit link: 192.168.45.76/30

  • Boris .77; Dmitry .78
  • .72-.75 remain outside the assigned component subnets
  • routing follows the same principles as before

44

subnet mask is another representation of prefix length

  • N one-bits followed by 32 - N zero-bits
  • /27 -> 255.255.255.224
  • /24 -> 255.255.255.0; /16 -> 255.255.0.0
  • network address = IP address bitwise-AND subnet mask

45

IPv4 TTL limits packet lifetime in router hops

  • each forwarding router decreases TTL
  • expired packet is discarded, normally with an ICMP report
  • prevents routing loops from circulating packets indefinitely

46

MTU limits packet size on a link

  • Ethernet commonly carries 1500-byte IP packets
  • IPv4 can fragment oversized packets when fragmentation is permitted
  • destination reassembles fragments
  • DF prevents router fragmentation; oversized delivery then fails with suitable feedback
  • IPv4 header checksum protects the header, not the entire payload

47

IPv4 has 2^32 possible bit patterns

  • reserved ranges and historical allocation reduce usable public supply
  • early classful allocations sometimes gave organizations much larger blocks than needed

48

address scarcity motivated conservation and a replacement protocol

  • IPv6 development began in the 1990s
  • smaller allocations and NAT prolonged IPv4 use

49

IPv6 addresses have 128 bits

  • 2^128 possible addresses
  • written as hexadecimal groups separated by colons
  • example: 2001:0db8:21b1:a742:0000:ff00:0042:8326
  • /64 provides 64 interface-address bits within a subnet
  • allocation sizes vary; the book's provider/customer sizes are examples

50

transition requires compatibility across independently operated networks

  • an IPv6-only service is unreachable to an IPv4-only client without translation
  • dual-stack deployments can serve both
  • book's claims about negligible IPv6 use describe its historical viewpoint

51

book discusses IPv4 exhaustion, allocation restrictions, and possible address reuse

  • exhaustion did not create one simultaneous global cutover
  • precise allocation limits and market predictions are time-dependent
  • fragmented allocations can increase routing-table complexity

52

author speculates about IPv6's future and possible alternatives

  • this is a prediction from the book, not a technical requirement or current usage fact
Conversions preserve the numeric value while choosing the byte representation required by the protocol.
Network byte order is most significant byte first. Open full size - Editable SVG

Datagrams and Streams

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
Detailed notes - 6.2.4: Datagrams and streams

1

IP delivers packets on a best-effort basis

  • packets may be lost, duplicated, or reordered
  • datagram exchange sends one addressed block of data at a time
  • an application needing reliability must add acknowledgments, timeouts, and retries
  • acknowledgments can cover groups of packets

2

splitting one object across datagrams requires reconstruction

  • include sequence numbers or positions
  • receiver restores order and detects missing fragments
  • missing information may need retransmission

3

minimal transport still needs two things

  • integrity checking for the payload, beyond IPv4's header checksum
  • identification of different communicating endpoints on one host

4

UDP = User Datagram Protocol

  • 16-bit source and destination port numbers identify endpoints
  • eight-byte header: source port, destination port, length, checksum
  • length includes UDP header and payload
  • UDP datagram is carried in an IP packet with source/destination IP addresses

5

stream transport presents a bidirectional byte stream

  • read/write-style operations at each endpoint
  • received bytes retain their transmitted order
  • no application-visible packet boundaries
  • failures can terminate the connection and appear through EOF/errors
  • successful write alone does not prove the peer application consumed the data

6

TCP = Transmission Control Protocol

  • provides ordered reliable byte-stream delivery or reports failure
  • handles acknowledgments, retransmission, and reassembly
  • uses port numbers like UDP
  • establish a connection before exchanging stream data
  • flow-control window limits outstanding data; it is not the packet size
  • TCP header is normally 20-60 bytes, including any options
  • OS implementation handles transport mechanics for applications
The sizes returned by TCP reads need not match the sizes of the sender's writes.
Datagrams preserve boundaries; streams preserve byte order. Open full size - Editable SVG
A connection is distinguished by both endpoints, not by the server port alone.
One server port supports many connected sockets. Open full size - Editable SVG
Simplified successful TCP opening: the handshake is transport setup, before application dialogue.
Connection establishment exchanges sequence numbers. Open full size - Editable SVG

Application Protocols

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.

Detailed notes - 6.2.5: Application-layer protocols

1

session, presentation, and application responsibilities often overlap in real protocols

2

Internet applications organize sessions without a distinct universal session layer

  • session behavior may be part of an application protocol or built above it

3

web login session can span many requests and connections

  • application associates requests using a session identifier
  • cookies are a common mechanism
  • transport connection lifetime and login-session lifetime are different

4

data representation also relies on agreements

  • character encodings: ASCII, UTF-8, ...
  • document/image formats: HTML, JPEG, PNG, ...
  • MIME describes media types, multipart content, and transfer encodings
  • e-mail attachments use MIME conventions
  • these are presentation-like responsibilities

5

application protocols provide actual user services

  • e-mail, the Web, messaging, ...

6

client-server model:

  • server waits for requests and provides a service
  • client initiates requests
  • one program can be server to one peer and client to another
  • these are roles in an interaction, not fixed hardware categories

7

many application protocols exchange text over a bidirectional stream

  • SMTP and HTTP/1.x are examples
  • a plain TCP terminal tool can expose their unencrypted exchanges
  • encrypted transports require the corresponding TLS support

8

book's SMTP example sends one test message through a mail server

  • connect to the server's TCP port 25
  • greeting -> EHLO -> MAIL FROM -> RCPT TO -> DATA -> message -> QUIT

9

transcript distinguishes three sources of text

  • '=': local shell/telnet output, not SMTP data
  • '>': commands/text sent by the client
  • other lines: server replies

10

SMTP server starts by sending a greeting

  • example: 220 pluto.unicontrollers.com ESMTP Postfix

11

greeting fields identify the service

  • 220: numeric response code
  • hostname: server identity
  • ESMTP: extended SMTP
  • Postfix: implementation name in this example

12

EHLO introduces the client and requests extended SMTP capabilities

  • parameter identifies the client host
  • older HELO form gives a simpler greeting exchange
  • server text after the numeric response is mainly explanatory

13

multiline EHLO response lists supported extensions

  • client uses only capabilities advertised by the server
  • this example needs only the basic mail-transfer commands

14

MAIL FROM supplies the envelope sender and begins a mail transaction

  • example: MAIL FROM: <test@stolyarov.info>

15

example successful reply: 250 2.1.0 Ok

16

SMTP clients interpret response codes, not decorative English wording

  • 250 means the requested action succeeded
  • 2.1.0 is an enhanced status code supplied by an extension
  • 'Ok' may be replaced with different explanatory text

17

RCPT TO supplies an envelope recipient

  • repeat for multiple recipients
  • server checks recipient validity and relay authorization
  • accepting mail for local users differs from relaying to unrelated destinations

18

open relay accepts mail from arbitrary senders for arbitrary destinations

  • abuse by spammers led operators to restrict relaying
  • relay policy matters when configuring a mail service
  • the book's dates describe its historical account

19

unauthorized relaying can be rejected

  • example: 554 5.7.1 ... Relay access denied

20

unknown recipient can also be rejected

  • example: 550 5.1.1 ... User unknown

21

DATA requests permission to send the message content

  • after accepted envelope sender and recipients
  • 354 tells the client to continue with the content

22

SMTP content format:

  • protocol line ending: CR LF, bytes 13 and 10
  • header fields, then a blank line, then message body
  • a line containing only '.' ends DATA
  • lines beginning with '.' require SMTP dot-stuffing
  • envelope MAIL FROM/RCPT TO and message From:/To: headers are distinct
  • final 250 reply accepts the message into the server's delivery process
  • server may add trace, delivery, date, and message-identifier headers

23

DNS MX records identify mail exchangers for a domain

  • book illustrates lookup with host -t MX domain
  • server accepting a message does not by itself prove final mailbox delivery

24

HTTP/1.1 example requests a site's root resource on TCP port 80

  • client sends GET / HTTP/1.1
  • Host field selects the intended site

25

shell/telnet messages precede the actual HTTP request

  • request data begins with the GET line and Host header

26

blank line terminates the HTTP request headers

  • example response begins HTTP/1.1 200 OK
  • response headers precede a blank line and the response body
  • HTTP client sends first, unlike SMTP's server greeting

27

both protocols use three-digit response codes, with different category meanings

  • SMTP: 2xx success; 3xx continuation; 4xx temporary failure; 5xx permanent failure
  • SMTP 354 invites message data; extensions can define other continuation replies
  • HTTP: 1xx informational; 2xx success; 3xx redirection
  • HTTP: 4xx client error; 5xx server error
  • HTTP's first digit does not classify errors as simply temporary/permanent

Domain Names

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.

Detailed notes - 6.2.6: Domain names

1

domain names are more convenient for people than numeric IP addresses

  • example: www.stolyarov.info

2

DNS = Domain Name System

  • distributed hierarchical database keyed by domain names
  • supports name-to-address lookup and many other record types
  • information for a name is not limited to one IP address

3

'domain' means an area or collection in several technical contexts

  • DNS uses it for a portion of the hierarchical namespace

4

names consist of dot-separated labels

  • ordinary hostname labels use letters, digits, and internal hyphens
  • www.stolyarov.info has labels www, stolyarov, info
  • hierarchy is read from the right: top-level domain, child, further child
  • internationalized hostnames use an encoded DNS representation
  • DNS labels in general are broader than the simplified hostname syntax

5

resource records have class, type, content, and TTL

  • TTL: how long a cached record may be retained
  • IN: Internet class used for ordinary Internet DNS
  • A: IPv4 address; AAAA: IPv6 address
  • MX: mail exchanger; SRV: service location; TXT: text data
  • one name can have several records

6

DNS domain is a subtree identified by a common name suffix

  • class.stolyarov.info lies within stolyarov.info and info
  • a subdomain is contained within its parent domain
  • root, written '.', contains the entire DNS namespace

7

hierarchy distributes authority across independently operated servers

  • authoritative servers hold a zone's official data
  • multiple servers improve availability
  • primary/secondary arrangements replicate zone data
  • change notifications can trigger early refresh; periodic checks still matter

8

parent can delegate a child domain to another set of servers

  • those servers answer authoritatively for the delegated portion
  • zone = authority's part of the domain, excluding delegated child zones

9

zone data can be stored in a text zone file

  • lookup finds authoritative servers and requests the desired record type
  • @ denotes the zone origin in the example file
  • relative names receive the origin suffix
  • trailing '.' marks an absolute domain name

10

$TTL sets the default record TTL in a zone file

  • example 86400 seconds = one day
  • individual records may override the default

11

important zone-file records:

  • SOA: zone authority information, serial, and timers
  • NS: authoritative name servers
  • parent delegation and child-zone NS records should be consistent
  • MX: mail server, with a preference value
  • A: IPv4 address
  • CNAME: alias to another domain name

12

wildcard record can provide answers for otherwise missing names

  • *.camp IN A 198.51.100.72
  • can synthesize answers for names below camp.stolyarov.info
  • actual wildcard rules depend on existing names and delegation boundaries

13

delegate example.stolyarov.info by adding NS records in its parent zone

  • example IN NS ns1.example.com.
  • example IN NS ns2.example.com.

14

glue avoids circular dependence when server names lie inside the delegated zone

  • resolver must know a server address before asking that server anything
  • parent includes needed A/AAAA address records alongside the delegation

15

root zone delegates top-level domains such as com, net, and info

  • recursive resolvers bootstrap from known root-server addresses
  • stable, redundant root service allows cached/bootstrap information to remain useful

16

root service uses 13 named server identities, a.root-servers.net through m.root-servers.net

  • logical identities are distinct from physical server instances
  • geographically distributed anycast instances provide service
  • book's instance counts and deployment locations are historical examples

17

recursive resolver caches records until their TTL expires

  • repeated lookups can reuse answers and delegation information
  • root servers are not contacted for every user query
  • caching and delegation distribute the load across the hierarchy
The resolver queries each authority. Dashed links show delegation; cached answers can skip this path.
DNS distributes authority through a name hierarchy. Open full size - Editable SVG
Section test (1 file) - 6.2.6: Domain names
Section test06 (06-02)In catalog
dns.txtText / 57 lines
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 Sockets

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.

Detailed notes - 6.3: Unix sockets

1

socket system calls expose networking to user programs

  • move from network concepts to implementing communicating processes

Address Families and Interaction Types

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.

Detailed notes - 6.3.1: Address families and communication types

1

socket is a kernel communication endpoint

  • local process operates on it through system calls
  • peer addresses it as an endpoint of communication
  • sockets also support local communication without a physical network

2

Unix socket is accessed through a file descriptor

  • close releases a descriptor
  • Internet endpoint address combines IP address and transport port

3

address representation depends on protocol family

  • IPv4 address: four bytes; IPv6: sixteen
  • historical IPX/SPX used network, host, and socket-number components
  • Unix-domain pathname sockets use filesystem paths

4

common socket API accommodates different families

  • choose an address family when creating the socket
  • new protocol support need not replace the basic syscall interface
  • applications use the appropriate family-specific address structures

5

socket type selects communication semantics

  • SOCK_DGRAM: datagrams
  • SOCK_STREAM: byte stream
  • other types exist but are outside this discussion

6

IP datagrams have finite size and no delivery/order guarantee

  • send one message; receive one message
  • loss, duplication, and reordering are possible
  • maximum UDP datagram size differs from path MTU
  • keeping packets within path MTU avoids IP fragmentation
  • IPv4 with 1500-byte MTU, 20-byte IP header, and 8-byte UDP header leaves 1472 payload bytes
  • the book's conservative 508-byte figure allows for a 60-byte IPv4 header within 576 bytes

7

stream socket exposes an ordered bidirectional byte stream

  • application need not handle packet reassembly or retransmission
  • errors can still interrupt delivery
  • no message boundaries; read sizes need not match write sizes

8

create with socket(family, type, protocol)

9

socket arguments:

  • AF_INET: IPv4 Internet addresses
  • AF_UNIX: communication within one machine
  • SOCK_STREAM or SOCK_DGRAM selects semantics
  • protocol = 0 selects the default for the family/type combination
  • AF_INET examples: IPPROTO_TCP for stream, IPPROTO_UDP for datagrams

10

socket returns a new file descriptor on success

  • -1 on error

Socket Addresses

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.

Detailed notes - 6.3.2: Socket addresses

1

bind assigns a local address to a socket

  • bind(sockfd, address, address_length)
  • sockfd: socket descriptor
  • address: pointer to the family-specific address structure
  • address_length: size in bytes, represented by socklen_t

2

bind returns 0 on success, -1 on error

  • address/port may already be in use
  • requested address may not be local
  • permissions may prevent binding a privileged port or pathname
  • check the result before continuing

3

IPv4 uses struct sockaddr_in

  • sin_family: AF_INET
  • sin_port: port number in network byte order
  • sin_addr: struct in_addr containing s_addr
  • s_addr: 32-bit IPv4 address in network byte order

4

address-family field identifies the concrete address representation

  • appears in each supported socket-address structure
  • field names differ between structures

5

IP address identifies an interface/address on a host

  • port distinguishes communication endpoints using that address
  • many processes can use different ports on the same host address

6

network byte order is big-endian

  • host byte order depends on CPU architecture
  • conversion functions make source portable: htons: host -> network, 16 bits htonl: host -> network, 32 bits ntohs: network -> host, 16 bits ntohl: network -> host, 32 bits

7

function names encode direction and width

  • h = host; n = network; s = 16-bit; l = 32-bit
  • 'long' here does not mean whatever size C long has on the platform
  • example: addr.sin_port = htons(7654);

8

low-numbered ports traditionally require privilege

  • TCP/UDP ports below 1024 are the conventional privileged range
  • root or appropriate capability/configuration can authorize binding
  • permission failure is reported by bind, commonly as EACCES

9

inet_aton converts textual IPv4 address to struct in_addr

  • inet_aton(text, &address.sin_addr)

10

inet_aton result:

  • nonzero: accepted address text
  • 0: invalid text
  • fill sin_family, convert sin_port with htons, then parse sin_addr
  • check parsing before using the address

11

inet_addr also converts IPv4 text

  • returns an address value for sin_addr.s_addr

12

inet_addr result is already in network byte order

  • do not apply htonl again
  • error value collides with the valid bit pattern for 255.255.255.255
  • inet_aton or inet_pton gives clearer validation

13

server can bind to all local IPv4 addresses

  • addr.sin_family = AF_INET;
  • addr.sin_port = htons(port);
  • addr.sin_addr.s_addr = htonl(INADDR_ANY);
  • kernel chooses a suitable source address for outgoing traffic

14

INADDR_ANY represents 0.0.0.0 for wildcard binding

  • useful for a local bind address, not as a remote destination
  • textual-address conversion is often used for the peer address instead
  • use the documented byte order for INADDR constants

15

struct sockaddr_in is declared through <netinet/in.h>

  • address conversion declarations are normally in <arpa/inet.h>

16

generic API takes struct sockaddr pointers

  • bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))
  • cast family-specific structure pointer at the call boundary
  • initialize the structure and handle bind failure

17

Unix-domain addresses use struct sockaddr_un from <sys/un.h>

  • sun_family = AF_UNIX
  • sun_path stores pathname bytes directly
  • Linux commonly provides 108 bytes, but capacity is platform-dependent
  • check path length rather than assuming an arbitrary name fits

18

pathname socket has a socket-type filesystem entry

  • bind creates it; directory permissions must allow creation
  • existing pathname may make bind fail
  • closing the socket does not automatically unlink the entry
  • remove the pathname with unlink when appropriate

19

pathname socket permission checks vary by OS

  • Linux uses write permission for relevant connection/send operations
  • do not assume identical checks on every Unix system
  • directory access restrictions also matter

20

other families provide their own address structures

  • same structures are used by bind and other address-taking socket calls
Tests & experiments (5 files) - 6.3.2: Socket addresses
Section test02 (06-03)In catalog
socket-00.cC / 30 lines
#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;
}
socket-01.cC / 29 lines
#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;
}
socket-02.cC / 34 lines
#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;
}

socket-03.cC / 32 lines
#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;
}

socket-04.cC / 29 lines
#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;
}

Datagram Sockets

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.

Detailed notes - 6.3.3: Sending and receiving datagrams

1

create a datagram socket with SOCK_DGRAM

  • bind when peers need a known local destination address/port
  • INADDR_ANY can cover all local IPv4 addresses
  • unbound UDP socket normally receives an automatic local address/port on first use
  • automatic binding suits a requester whose peer replies to the observed source

2

sendto sends a datagram; recvfrom receives one

  • sendto(fd, buf, len, flags, destination, destination_length)
  • recvfrom(fd, buf, len, flags, source, &source_length)
  • byte counts use ssize_t results and size_t buffer lengths

3

common arguments:

  • fd: socket descriptor
  • buf: bytes to send or storage for received bytes
  • len: send length or receive-buffer capacity
  • flags = 0 for basic use
  • check returned byte count/-1 rather than assuming success

4

sendto destination has the selected family's address structure

  • sockaddr_in for AF_INET; sockaddr_un for AF_UNIX
  • pass actual structure size as destination length
  • use socklen_t for variables whose addresses are passed as length pointers

5

source comments on the history of socklen_t

  • practical rule: use the API's declared type instead of guessing int or size_t

6

recvfrom can return the sender's address

  • initialize socklen_t source_length to available structure capacity
  • pass its address
  • call updates it with the address length
  • receive buffer must be large enough; oversized datagrams may be truncated

7

choose datagram size with path constraints in mind

  • UDP's protocol limit and the path's unfragmented payload limit are different
  • large messages may require fragmentation or application-level subdivision
  • path-MTU handling is a separate technical topic

8

naive request/reply sequence can block forever

  • sendto(request), then blocking recvfrom(reply)
  • request may be lost -> peer never knows to answer
  • reply may be lost -> requester keeps waiting

9

bound waiting time and decide what to do when it expires

  • book suggests SIGALRM as one possible timeout mechanism
  • alarm-handler/restart behavior must allow the wait to be interrupted
  • retries require a policy, not an infinite blind resend loop

10

other receive-timeout mechanisms:

  • select can wait for socket readiness or a deadline
  • SO_RCVTIMEO sets a socket receive timeout through setsockopt
  • struct timeval contains seconds and microseconds

11

example SO_RCVTIMEO = 3.5 seconds

  • tv_sec = 3; tv_usec = 500000
  • setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))
  • check option-setting and receive results

Stream Sockets and Client-Server Programs

A TCP server creates a listening socket:

int listen(int sockfd, int qlen);

The usual server setup:

  1. create socket with socket(AF_INET, SOCK_STREAM, 0)
  2. optionally set SO_REUSEADDR
  3. bind local address with bind
  4. mark it as listening with listen
  5. accept client connections with accept

Accept 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.

Detailed notes - 6.3.4: Stream sockets and client-server roles

1

stream communication begins by establishing a connection

  • client initiates
  • server waits for and accepts connection requests
  • TCP provides this behavior for the Internet stream sockets discussed here

2

server has a listening socket and separate connected sockets

  • listening endpoint receives connection requests
  • accepted connection gets a new socket for actual data exchange
  • listener remains available for further clients

3

server setup: socket -> bind -> listen

  • listen(sockfd, backlog)

4

listen backlog concerns pending connections awaiting acceptance

  • limits the relevant kernel queue, subject to OS rules
  • does not limit total established client sessions
  • queue overflow behavior depends on the implementation/protocol

5

choose backlog with workload and system limits in mind

  • old examples' value 5 is historical
  • kernel may cap requested backlog
  • book's value 128 is not a universal modern maximum
  • sustained overload needs capacity/design changes; queue size mainly absorbs bursts

6

accept obtains the next pending connection

  • accept(listenfd, peer_address, &peer_address_length)

7

accept address arguments report the peer

  • initialize socklen_t length to the supplied address-storage capacity
  • call writes address and updates length
  • same input/output-length pattern as recvfrom

8

accept returns a new connected descriptor, or -1 on error

  • blocking listener waits if no connection is ready
  • server now has listener plus connected client descriptor
  • deciding when to accept versus read a client leads to the next chapter's scheduling problem

9

client setup: socket -> connect

  • explicit bind is optional for ordinary outgoing TCP connections
  • kernel can select local address and port
  • connect(sockfd, server_address, server_address_length)

10

connect takes the remote server endpoint

  • use the appropriate family-specific structure and size
  • normal blocking success: 0
  • failure: -1 with errno

11

connected stream supports read and write

  • server uses accept's returned descriptor
  • client uses the descriptor passed to connect
  • recv/send add a flags argument
  • handle partial reads/writes and errors

12

UDP connect sets a default peer without a TCP-style handshake

  • configures the local socket; does not establish a reliable stream
  • received datagrams are filtered to the selected peer
  • read/write or recv/send can then omit destination arguments
  • datagram boundaries and UDP reliability limitations remain

13

close releases one descriptor reference

  • dup/dup2 or fork can create several references to the same socket
  • closing one of several references does not normally close the connection

14

last descriptor close initiates socket cleanup

  • queued transmission may continue in the kernel after close returns
  • orderly peer shutdown produces read/recv result 0 after buffered data is consumed
  • connection errors can instead be reported as errors

15

shutdown changes permitted communication directions

  • shutdown(sockfd, how)

16

shutdown directions:

  • SHUT_RD: stop receiving
  • SHUT_WR: stop sending
  • SHUT_RDWR: both
  • use symbolic names rather than historical numeric values 0, 1, 2

17

shutdown affects the socket itself, across all descriptor references

  • does not release descriptors
  • does not replace the need for close
  • descriptor resources remain allocated until closed

18

SHUT_WR performs a half-close

  • queued output precedes the end-of-stream indication
  • peer reads remaining bytes, then sees EOF
  • caller can continue receiving
  • example: client sends request, half-closes output, then reads server's response

19

SHUT_RD declares that the application will receive no more data

  • further reads/data handling follow the socket implementation's semantics
  • do not depend on identical treatment of already queued data across systems

20

ordinary close can return while kernel still has unsent output

  • later transmission errors cannot be reported through that closed descriptor
  • closing is not an application-level acknowledgment of successful processing

21

SO_LINGER changes close behavior

  • disabled: ordinary background completion behavior
  • enabled with zero interval: typically abortive close
  • enabled with positive interval: can wait for transmission progress up to a limit
  • precise timeout/error behavior is platform-dependent

22

SO_LINGER is configured with setsockopt

  • consult target-system socket documentation for exact behavior

23

transport acknowledgment does not prove the remote application processed data

  • SO_LINGER alone cannot establish that stronger guarantee
  • application protocols need their own confirmation when it matters
accept returns another descriptor, leaving the listening socket ready for further connection requests.
A listener and its accepted sockets have different jobs. Open full size - Editable SVG
Tests & experiments (12 files) - 6.3.4: Stream sockets and client-server roles
Section test04 (06-03)In catalog
socket-00.cC / 101 lines
#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;
}
socket-00c.cC / 36 lines
#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;
}
socket-01.cC / 79 lines
#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;
}
socket-01c.cC / 47 lines
#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;
}
Section testTCP client/server test suite (tcp-programs)In catalog
MakefileMake / 13 lines
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 $@

program-a.cC / 104 lines
/* 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;
}
program-a0.cC / 59 lines
/* 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;
}
program-a1.cC / 94 lines
/* 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;
}
program-b.cC / 67 lines
/* 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-b0.cC / 67 lines
/* 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;
}
test.shShell / 15 lines
./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
test1.shShell / 17 lines
#!/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

TCP Port Reuse and TIME_WAIT

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.

Detailed notes - 6.3.5: Reusing a TCP server address

1

restarting a TCP server can encounter address-in-use errors

  • old connection state may remain after processes finish
  • TIME_WAIT helps keep delayed packets from being confused with later connections
  • it normally arises during orderly active close too, not only after a crash

2

bind may fail while relevant old state remains

  • waiting period is implementation-dependent
  • always check bind, otherwise subsequent failures obscure the original cause

3

SO_REUSEADDR can permit normal server-address reuse

  • set it on the intended listener before bind
  • use setsockopt(sockfd, level, option, value_pointer, value_length)
  • reuse remains subject to platform rules and existing active bindings

4

example option setup:

  • int opt = 1;
  • setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  • SOL_SOCKET: generic socket option level
  • optval points to the value; optlen gives its size
  • check the result before proceeding to bind/listen

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.

Detailed notes - 6.3.6: Sockets between related processes

1

socketpair creates an already-connected pair for local communication

  • convenient alternative to two one-way pipes
  • socketpair(family, type, protocol, descriptors)

2

typical call: socketpair(AF_UNIX, SOCK_STREAM, 0, sv)

  • sv is an int array of two elements
  • returns 0 on success, -1 on failure
  • sv[0] and sv[1] are both readable and writable
  • create pair before fork so related processes inherit endpoints
  • each process closes the endpoint copies it does not need
  • then exchange data through the remaining connected endpoints
Section test (1 file) - 6.3.6: Sockets between related processes
Section test06 (06-03)In catalog
socket-00.cC / 44 lines
#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;
}

Ordering of Actions in Servers

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.

The Blocking Problem

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
Show the complete program
#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;
}
Detailed notes - 6.4.1: The ordering problem

1

a server has several possible sources of work

  • listening socket: new connection requests
  • accepted sockets: data from existing clients
  • blocking in accept prevents it from handling existing connections
  • a new connection might not arrive for an arbitrarily long time

2

blocking in read / recv has the same problem

  • one client may send nothing for a long time
  • meanwhile other clients and new connection requests go unserved

3

writes can block too

  • network throughput and kernel buffers are finite
  • sending a large file to one slow client can delay every other client

4

restaurant analogy: one waiter, separate booths, and an entrance

  • waiting at the entrance = accept
  • waiting for one table's order = read from one connection
  • waiter cannot see all tables and the entrance simultaneously
  • any table or a new arrival may require attention at any moment

5

one possible approach: make every socket nonblocking and poll them repeatedly

  • flags = fcntl(sd, F_GETFL);
  • fcntl(sd, F_SETFL, flags | O_NONBLOCK);
  • preserve existing status flags when adding O_NONBLOCK
  • read / accept with nothing available return immediately
    • normally -1 with EAGAIN or EWOULDBLOCK
  • write may transfer only part of the requested data
    • positive return = number of bytes accepted
    • unavailable output space -> -1 / EAGAIN or EWOULDBLOCK
  • -> repeatedly trying sockets without work is busy waiting

6

busy waiting wastes CPU time

  • competes with other processes
  • can exhaust a process's CPU-time limit
  • prevents useful idle time and increases energy consumption

7

an idle server should consume little CPU

  • some services receive no requests for long periods
  • heavy traffic also does not justify useless polling

8

first useful solution: a separate worker process for each client

  • parent accepts connections
  • child waits for and serves its own client
  • analogy: receptionist plus one waiter per table

9

second solution: wait for notification that something needs attention

  • analogy: doorbell and call button at every table
  • timer handles actions due after a specified interval
  • one process can sleep until a relevant event occurs
  • -> I/O multiplexing

10

the following subsections develop worker processes and event-driven operation

One Process per Client

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.

Detailed notes - 6.4.2: A worker process for each connection

1

parent accepts connections; each child serves one connection

setup:

  • socket(AF_INET, SOCK_STREAM, 0)
  • enable SO_REUSEADDR
  • fill sockaddr_in with family, htons(port), and htonl(INADDR_ANY)
  • bind, then listen with the example's queue length of 16

main loop:

  • accept -> obtain client descriptor and peer address
  • fork a worker
  • child closes listening socket, serves client, then exits
  • parent closes its copy of the client descriptor and accepts again
  • example repeatedly calls wait4(-1, NULL, WNOHANG, NULL) until no more terminated children are ready to reap
  • real code must also handle accept and fork failures

2

reaping only after another accept can leave zombies indefinitely

  • parent may remain blocked waiting for a new connection
  • handle SIGCHLD and reap completed children promptly
  • reap in a loop because several children can finish before notification
  • accept may then return -1 / EINTR; this is an interruption to handle

Event-Driven Programming

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);
    }
}
Show the complete program
#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;
}
Detailed notes - 6.4.3: Event-driven programming

1

one process per client is not always convenient

  • process creation costs matter at high connection rates
  • clients may interact through shared application state
  • example: players affect the same multiplayer game
  • separate workers then need communication and coordination
  • each worker may still need to choose between client input and peer updates

2

alternative: one process handles many event sources without busy waiting

  • sleep while none requires work
  • learn which source is ready
  • perform a useful operation, then consider other events

3

event-driven program:

  • main loop waits for events and reacts to them
  • examples: network servers and graphical applications
  • GUI events include keyboard input, mouse movement, and clicks

4

each iteration has two phases:

  • obtain ready events
  • dispatch them to event handlers

5

event handlers must return promptly

  • one long handler delays every other event
  • acceptable duration depends on response-time requirements
  • GUI pauses are visible; network clients may time out

6

do not issue an operation that can block indefinitely inside a handler

  • its waiting time is outside the event loop's control
  • one blocked handler stops the entire process from serving other events

7

sequential application logic must become resumable

  • remember each client's current stage
  • when its event arrives, perform the next available step
  • save the resulting state and return to the main loop
  • continue later when another relevant event arrives
Rebuild descriptor sets every iteration; select overwrites them with the ready subsets.
Wait for readiness, then do bounded work. Open full size - Editable SVG

Waiting for Events with select

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.

Detailed notes - 6.4.4: Obtaining events in Unix: select

1

efficient event waiting needs kernel support

  • kernel blocks the process when there is no work
  • process does not consume CPU repeatedly checking sources

2

wait for any event from a set:

  • incoming client data
  • new connection request
  • output buffer space becoming available
  • elapsed timeout
  • caught signal

I/O multiplexing: readiness selects which I/O operation to attempt next

3

Unix readiness interfaces include select and poll

  • similar purpose, different representations and capabilities
  • platform-specific alternatives include BSD kqueue and Linux epoll
  • an interface may be a library wrapper around another kernel interface
  • this subsection develops select

4

select(n, readfds, writefds, exfds, timeout)

  • readfds: descriptors to check for readable input / pending connections
  • writefds: descriptors to check for writable output
  • exfds: descriptors to check for exceptional conditions
  • n = highest descriptor number being checked + 1
    • not the number of descriptors placed in the sets
  • timeout: maximum wait, even if no descriptor becomes ready
  • a caught signal can also interrupt the wait

5

fd_set represents a descriptor set

  • FD_ZERO(&set): empty it
  • FD_SET(fd, &set): add fd
  • FD_CLR(fd, &set): remove fd
  • FD_ISSET(fd, &set): test membership
  • use these macros instead of assuming the internal representation

6

fd_set has a descriptor-number limit

  • valid members satisfy 0 <= fd < FD_SETSIZE
  • largest representable descriptor is FD_SETSIZE - 1

7

FD_SETSIZE and the process's descriptor limit are different limits

  • the book commonly encountered FD_SETSIZE = 1024
  • do not assume every descriptor the process can open fits in fd_set
  • use an appropriate alternative when descriptor numbers exceed this range

8

timeout uses struct timeval

  • tv_sec: whole seconds
  • tv_usec: additional microseconds, 0 through 999999
  • 5.3 seconds -> tv_sec = 5, tv_usec = 300000

9

select may modify the timeout structure

  • behavior differs between implementations
  • rebuild it before every call
  • do not rely on it retaining either its original value or remaining time

10

unused set pointers may be NULL

  • timeout = NULL: no time limit
  • no descriptor sets + finite timeout: timed wait
  • no descriptor sets + no timeout: wait until interrupted by a signal

11

select return values:

  • -1: error; inspect errno
    • EINTR: interrupted by a caught signal
    • other errors include an invalid open-descriptor reference
  • 0: timeout expired
  • positive: number of ready entries across the descriptor sets
    • one descriptor can contribute in more than one set

input sets are overwritten with the corresponding ready subsets

  • rebuild them on the next iteration
  • use FD_ISSET to locate ready descriptors
  • readiness includes EOF and some error conditions; check the actual I/O result

12

exfds is often unused in simple socket applications

  • TCP out-of-band / urgent-data notification is one use
  • exceptional conditions are not a general replacement for checking I/O errors

13

readability means a read can produce a result without waiting

  • available input can be less than the requested amount
  • EOF is readable too: read returns 0 immediately
  • readiness does not promise a complete application-level message

14

readfds also supports sockets used through other operations

  • listening socket: a pending connection can be accepted
  • datagram socket: a datagram can be received
  • use the corresponding accept / receive operation after notification
  • nonblocking descriptors also protect against readiness changing before use

15

writability does not promise space for an arbitrarily large write

  • some output can proceed immediately
  • a blocking write requesting more can still wait
  • -> readiness alone is insufficient to guarantee a responsive event loop

16

robust output uses a nonblocking socket and a per-client output buffer

  • wait for writability before attempting pending output
  • inspect the returned byte count
  • remove only bytes actually accepted by write / send
  • keep the remainder for a later writable event
  • handle EAGAIN / EWOULDBLOCK and interruptions appropriately
  • small writes simplify the book's examples, but can still block in principle

17

watch for writability only when there is output to send

  • sockets with available buffer space are usually writable immediately
  • watching an idle writable socket makes select return repeatedly
  • -> accidental busy waiting even though select is being used

18

server-loop outline:

  • clear readfds and writefds; begin max_d with the listening descriptor
  • add listening socket to readfds
  • add client sockets to readfds
  • add a client to writefds only when its output buffer contains data
  • update max_d and construct the timeout
  • call select(max_d + 1, ...)
  • -1: handle EINTR or other error; do not inspect readiness sets
  • 0: handle timeout; do not inspect readiness sets
  • listening socket readable: accept and record the new client
    • configure required nonblocking behavior on accepted descriptors
  • client readable: read input, handle EOF/errors, and process received data
  • client writable: attempt queued output and retain unsent bytes
  • return to the beginning and rebuild all sets

19

two phases remain distinct in that outline

  • preparation and select obtain events
  • the rest of the iteration handles the events reported
Book example (1 file) - 6.4.4: Obtaining events in Unix: select
Book exampleBook example: tcp_questn.cIn catalog
tcp_questn.cC / 319 lines
#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;
}

Sessions as Finite Automata

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;
}
Detailed notes - 6.4.5: A session as a finite-state machine

1

an event-driven interaction cannot rely on a blocking sequence of statements

  • the application must preserve progress while servicing other clients

2

read / recv may return only part of one client request

  • do not issue another blocking read just to finish that request
  • save the fragment and return to the event loop
  • append later fragments from the same client
  • after each read, check whether the request is complete

3

each client needs its own accumulation buffer

  • TCP supplies a byte stream, without application-message boundaries
  • a buffer can contain a partial request, a complete request plus a fragment, or several complete requests
  • framing logic must distinguish and preserve these cases

4

application protocols also contain sequences of separate exchanges

  • receiving complete requests is only one part of maintaining the dialogue
  • remember which exchange each client has reached

5

example questionnaire asks, in order:

  • name
  • age
  • town
  • favorite band

ordinary Pascal version alternates write(question) with readln(answer)

6

the same sequential dialogue can use socket write and repeated reads

  • suitable when the process serves only that client
  • e.g. the worker-process approach

7

one blocking dialogue is unsuitable for a shared event loop

  • a distracted client can make every other client wait
  • a deliberately silent client can make the same failure persistent

8

on each client's readable event:

  • append bytes to its buffer
  • if no complete line exists, keep state unchanged and return
  • otherwise extract a line, record the answer, and advance the dialogue
  • queue the next question and return promptly
  • other clients can progress between this client's steps

9

session state records the current stage of communication

  • changes when relevant requests, responses, or other events arrive

10

finite-state machine (FSM):

  • predefined set of states
  • events cause transitions between states
  • client-session logic naturally fits this representation

11

questionnaire state diagram:

  • creation: ask name; enter name / start
  • name received: save it, ask age, enter age
  • valid age received: save it, ask town, enter town
  • town received: save it, ask band, enter band
  • band received: save it, thank the user, enter finish
  • invalid age: remain in age and ask again

transitions can have both a condition and associated actions

12

use a distinct error state for a session that cannot continue

  • example: input buffer fills before a newline arrives
  • a 2048-byte limit is ample for this example's expected answers
  • report an overlong line and terminate that session
  • error must remain distinguishable from successful completion

13

more complex protocols can branch according to previous answers

  • several transitions may leave one state
  • large diagrams can be split into groups with separate diagrams
  • another diagram describes transitions between those groups

14

implement states as stored values

  • an enum can contain start, name, age, town, band, finish, error
  • fsm_name = fsm_start gives the initial state two names
  • each session stores its own current state

15

state information can include several variables

  • counters, parameters, and saved answers can accompany the state enum
  • application state is explicit data retained between handler calls

16

FSM reacts to events supplied by the surrounding program

  • event acquisition remains outside the FSM step
  • FSM receives a completed line and decides what it means
  • it must not block waiting to obtain its next event

17

example struct session contains:

  • fd: client socket descriptor
  • buf[2048]: accumulation buffer
  • buf_used: number of occupied bytes
  • state: current FSM state
  • name, town, band: pointers to saved answers
  • age: parsed integer

18

make_new_session(fd) initializes a newly accepted connection

  • allocate the session structure and record fd
  • set buf_used = 0 and state = fsm_start
  • initialize answer pointers to NULL and age to -1
  • send / queue the first question, "What is your name?"
  • return the initialized session

19

session_send_string isolates outgoing text handling

  • example simply calls write(fd, s, strlen(s))
  • every question and diagnostic uses the same helper

20

that helper is deliberately simplified for this small demonstration

  • a fully nonblocking implementation queues outgoing data
  • tracks writable events and partial writes
  • tiny messages do not provide an unconditional guarantee against blocking

21

session_fsm_step(sess, line) receives ownership of a complete allocated line

  • name state: retain line as name; ask age; enter age
  • age state: parse / validate through a helper, then free the input line
  • town state: retain line as town; ask band; enter band
  • band state: retain line as band; send thanks; enter finish
  • unexpected finish/error invocation: free the supplied line

ownership avoids copying saved text unnecessarily

22

switch(state) selects the action for the current FSM state

age helper:

  • use strtol with base 10
  • reject empty input, trailing invalid characters, or an age outside 0-150
  • invalid answer: ask again without changing state
  • valid answer: save age, ask town, enter town
  • robust parsing also checks strtol overflow before narrowing to int

23

main loop should use a session interface instead of manipulating the FSM

session_do_read:

  • read into buf + buf_used, leaving existing data intact
  • update buf_used after a successful read
  • call session_check_lf to extract and process complete input
  • if a line has exhausted the buffer, report it and mark error
  • return 1 to retain the session, 0 when it should be closed
  • EOF, fatal read errors, and finish end this example's session
  • distinguish retryable EINTR / EAGAIN when extending it to nonblocking I/O

24

session_check_lf connects byte-stream handling with the FSM

  • search the occupied buffer for '\n'
  • no newline: leave the fragment buffered and return
  • copy bytes before newline to a separately allocated, NUL-terminated string
  • remove that line and newline from the buffer
  • use memmove to shift remaining bytes and reduce buf_used
  • strip a trailing '\r' to accept CRLF input
    • check that the line is nonempty before examining its last character
  • transfer line ownership to session_fsm_step

for pipelined input, process additional complete buffered lines promptly

  • the shown one-line helper can otherwise leave a line waiting for new data
  • stop when the session finishes or errors; keep each event's work bounded

25

tcp_questn.c in the book's examples contains the complete questionnaire server

  • accepts TCP clients
  • runs this session FSM
  • saves completed questionnaire results in a text file

26

explicit states replace information previously carried by control flow

  • sequential version: current instruction position records dialogue progress
  • event-driven version: stored state records that progress
  • -> programming in terms of explicit states

An event-driven server cannot rely on a simple sequence of blocking calls such as:

read request -> compute response -> write response
Keep a separate input buffer and dialogue state for every connected client.
Frame complete lines before advancing the session. Open full size - Editable SVG

Nonblocking connect

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 */
}
Detailed notes - 6.4.6: Establishing a connection without blocking

1

a program can act as both server and client

  • while serving its own clients, it may request data from another server

2

ordinary connect can block until establishment succeeds or fails

  • this can take long enough to stall the whole event loop
  • outgoing connections therefore need nonblocking handling too

3

make the socket nonblocking before connect

possible outcomes:

  • 0: connection completed immediately
  • -1 / EINPROGRESS: attempt has started but is still pending
  • another error: handle the failed attempt
  • immediate success must be handled even if it is uncommon

4

a pending connect uses writable readiness

  • put its socket in writefds
  • writability reports that the connection attempt has finished
  • completion can mean success or failure
  • this is a separate use of writefds from queued application output

5

check the outcome with getsockopt

  • level = SOL_SOCKET
  • option = SO_ERROR
  • provide an int to receive the socket error
  • provide socklen_t initialized to sizeof(that int)
  • getsockopt(sd, SOL_SOCKET, SO_ERROR, &opt, &optlen)
  • optlen is an input/output size parameter
  • check getsockopt's own return value before using opt

6

after successful getsockopt:

  • opt = 0: connection established
  • opt != 0: connection failed; opt contains its error code
  • move the connection into its next application state or clean it up

Signals as Events and pselect

Signals can be treated as events in a main loop, but there is a race:

  1. main code checks a flag set by a signal handler
  2. no flag is set
  3. signal arrives immediately after the check
  4. main code enters select
  5. no descriptor event happens for a long time

The 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.

Detailed notes - 6.4.7: Signals as events: pselect

1

signal notifications can become events in a select-based program

  • the difficulty is coordinating their delivery with the event loop's wait
  • the same signal-mask principles apply as in sigsuspend

2

a caught signal interrupts select with -1 / EINTR

  • this lets the main loop react to a signal
  • but the loop also spends time outside select

3

minimal signal handler records that work is pending

  • example: SIGUSR1 updates usr1_caught
  • use volatile sig_atomic_t for a simple pending flag
  • ordinary signals can coalesce; the flag is not a reliable count of sends

4

perform substantive work in an ordinary main-loop function

  • example name: actions_on_usr1
  • can use facilities unsuitable inside the asynchronous signal handler
  • must still return promptly like every event handler

example sequence: preparation A -> select -> code B -> process signal flag -> C

  • signal during select or B is handled by that iteration's flag check

5

signal during A or C creates a lost-wakeup problem

  • handler records the signal before the next select begins
  • select does not know there is already pending application work
  • it may wait indefinitely for a different event

6

visible effect: a control request appears to have been ignored

  • e.g. administrator sends SIGUSR1 to request configuration reload
  • the flag is set, but reload waits until an unrelated event wakes select

7

first attempted fix: process the flag immediately before select

  • reduces the vulnerable interval
  • does not make checking the flag and entering the wait atomic

8

a signal can still arrive between the final check and select

  • small probability does not remove the race

9

this is the same problem as checking a flag before pause

  • sigsuspend solves it by atomically replacing the mask while waiting
  • keep the relevant signal blocked outside the wait
  • allow its delivery only during the wait

10

pselect adds atomic signal-mask replacement to select-style waiting

  • pselect(n, readfds, writefds, exfds, timeout, sigmask)
  • sigmask: pointer to the mask active during the wait
  • previous mask restored before return
  • timeout uses const struct timespec, not timeval
    • tv_sec: whole seconds
    • tv_nsec: nanoseconds, 0 through 999999999
  • specified interface leaves the supplied timeout unchanged

11

for this pattern, sigmask temporarily permits the awaited signal

  • mask still lists blocked signals
  • omit the awaited signal from the temporary mask
  • the normal mask outside pselect keeps it blocked

12

SIGUSR1 event-loop pattern:

  • create a set containing SIGUSR1
  • sigprocmask(SIG_BLOCK, &mask, &orig_mask)
  • install the handler; preserve the original mask
  • call pselect with a temporary mask that permits SIGUSR1
    • using orig_mask assumes it did not already block SIGUSR1
  • signal can now run its handler during the wait and interrupt it
  • after return, normal blocking is restored
  • inspect the flag, perform the work, and clear the flag while SIGUSR1 is blocked
  • continue dispatching other events; repeat with rebuilt descriptor sets

13

ordinary select can be sufficient when bounded notification delay is acceptable

  • a short periodic timeout ensures the flag is checked regularly
  • e.g. a 0.1-second timeout bounds most waiting delay to roughly that interval plus time spent in other handlers
  • pselect removes the signal-check / wait race without periodic polling

Previous: Operating Systems Reading map Next: Parallel Programming

Comments

Leave a comment Sign in All comments