Network Programming — Free Notes & Tutorial
Free Network Programming notes for BTech CS — sockets API, TCP/UDP client-server design, I/O multiplexing with select and poll, socket options, DNS, daemons and inetd, broadcasting, multicasting, raw sockets, ping, traceroute and libpcap, with all lab programs in C. 100% free.
This Network Programming course is part of Siksha Sarovar and is 100% free for students in India — no sign-up required to read. It contains 15 structured lessons with examples, and pairs with our free online compiler and AI tutor.
What you will learn
- Sockets API
- Socket
- Bind
- Listen
- Accept
- Connect
- Fork
- Concurrent servers
- TCP echo client-server
- UDP sockets
- Select
- Poll
- Shutdown
- Socket options
- Readv/writev
- Recvmsg/sendmsg
- DNS
- Getaddrinfo
- Daemons
- Inetd
- Broadcasting
- Multicasting
- SNTP
- Raw sockets
- Ping
- Traceroute
- BPF
- Libpcap
- Pseudo-terminals
- RPC
Course content (15 lessons)
- Course Introduction: Programming the Network, Not Just Studying It — Welcome to Network Programming Computer Networks taught you how the Internet works — layers, protocols, headers. Network Programming teaches you to write the programs at both ends…
- Unit 1: Protocol Foundations — OSI, Unix Standards, TCP & UDP — 1.1 Where socket programs sit in the layer cake The sockets API is the door between the application process and the kernel's transport layer. Everything above the dotted line is…
- Unit 1: Socket Address Structures, Value-Result Arguments & Byte Ordering — 2.1 The address structures — the API's luggage Every socket function passes addresses via structures. IPv4: IPv6 uses struct sockaddr in6 ( sin6 family = AF INET6 , 128-bit sin6…
- Unit 1: Elementary TCP Sockets — socket to accept, fork & Concurrent Servers — 3.1 The call ladder This diagram is the exam answer for "explain the socket functions used by a TCP client and server". 3.2 The functions, one by one int socket(int family, int…
- Unit 2: The TCP Echo Client–Server, Signals & Crash Scenarios — 1.1 The echo pair — the course's laboratory animal The server echoes back every line a client sends. Server child logic and client loop: Normal startup: server…
- Unit 2: Elementary UDP Sockets — 2.1 The UDP API — two new calls No connections: each datagram carries its destination / reveals its source. No listen, no accept, no fork needed — one socket serves every client ,…
- Unit 2: I/O Multiplexing — I/O Models, select, shutdown & poll — 3.1 The five I/O models (the canonical comparison) Model Wait for data Copy data to process Blocks where? :--- :--- :--- :--- Blocking I/O process blocks process blocks the whole…
- Unit 2: Socket Options & Advanced I/O Functions — 4.1 getsockopt / setsockopt level selects the protocol layer: SOL SOCKET (generic), IPPROTO IP (IPv4), IPPROTO IPV6 , IPPROTO ICMPV6 , IPPROTO TCP . Most options are integer flags…
- Unit 3: Name & Address Conversions — DNS, Resolver & IPv6 Support — 1.1 The DNS in five lines Programs use names ( www.example.com ); packets need addresses . The DNS is the distributed, hierarchical database that maps between them. Resource…
- Unit 3: Daemon Processes, syslog & the inetd Superserver — 2.1 What a daemon is A daemon is a long-running background process with no controlling terminal — servers (sshd, httpd, named, crond) all daemonise at startup. No terminal means…
- Unit 3: Broadcasting — One-to-All on the LAN & Race Conditions — 3.1 The four addressing modes Mode Delivery Support :--- :--- :--- Unicast one sender → one receiver everywhere Broadcast one → all hosts on a subnet IPv4 only (IPv6 dropped it)…
- Unit 3: Multicasting — Groups, Socket Options, MBone & SNTP — 4.1 Multicast addresses and group membership Broadcast disturbs everyone; multicast delivers only to hosts that joined a group . IPv4 class D: 224.0.0.0 – 239.255.255.255 — a…
- Unit 4: Raw Sockets — Ping, Traceroute & an ICMP Daemon — 5.1 What raw sockets are for TCP and UDP sockets only carry TCP and UDP. A raw socket ( SOCK RAW ) opens the trapdoor to the IP layer itself, enabling programs to: 1. send/receive…
- Unit 4: Datalink Access — BPF, DLPI, SOCK_PACKET, libpcap & the UDP Checksum — 6.1 One layer lower still Raw sockets see IP datagrams addressed to (or from) this host . Datalink access captures entire frames — anyone's — straight from the NIC (in promiscuous…
- Unit 4: Remote Login — Terminals, Pseudo-Terminals & RPC Transparency — 7.1 Terminal line disciplines and modes Between a terminal device and the processes reading it sits the kernel's terminal line discipline — the layer that turns raw keystrokes…
Course Introduction: Programming the Network, Not Just Studying It
Welcome to Network Programming
Computer Networks taught you how the Internet works — layers, protocols, headers. Network Programming teaches you to write the programs at both ends of the wire: clients, servers, daemons, ping, traceroute, even packet sniffers. The toolkit is the sockets API — the C interface (born in 4.2BSD UNIX, 1983) that still underlies every networked program: browsers, game servers, Node.js, Python's socket module, all of them.
The guiding textbook tradition for this paper is W. Richard Stevens' UNIX Network Programming — the lessons follow its path and its famous client/server examples.
The journey of this course
How this course is organised
| Syllabus block | Lessons that cover it |
|---|---|
| OSI model, Unix standards, TCP/UDP, connection establishment, buffer sizes, standard services | Unit 1 → "Protocol Foundations" |
| Socket address structures, value-result arguments, byte ordering | Unit 1 → "Socket Address Structures & Byte Ordering" |
| socket, connect, bind, listen, accept, fork/exec, concurrent servers, close | Unit 1 → "Elementary TCP Sockets" |
| TCP echo client/server, signal handling, server crash/reboot scenarios | Unit 2 → "The TCP Echo Client–Server & Its Failure Modes" |
| Elementary UDP sockets, lost datagrams, no flow control, outgoing interface | Unit 2 → "Elementary UDP Sockets" |
| I/O models, select, poll, shutdown, batch input | Unit 2 → "I/O Multiplexing" |
| getsockopt/setsockopt, socket states, all option levels | Unit 2 → "Socket Options & Advanced I/O" (first half) |
| Socket timeouts, recv/send flags, readv/writev, recvmsg/sendmsg, ancillary data | Unit 2 → "Socket Options & Advanced I/O" (second half) |
| DNS, gethostbyname, resolver, IPv6 functions, uname | Unit 3 → "Name & Address Conversions" |
| Daemons, syslog, daemon_init, inetd | Unit 3 → "Daemon Processes & the inetd Superserver" |
| Broadcasting, unicast vs broadcast, race conditions | Unit 3 → "Broadcasting" |
| Multicasting, mcast_join, MBone, SNTP | Unit 3 → "Multicasting & SNTP" |
| Raw sockets, ping, traceroute, ICMP daemon | Unit 4 → "Raw Sockets" |
| BPF, DLPI, SOCK_PACKET, libpcap, UDP checksum | Unit 4 → "Datalink Access" |
| Terminal line disciplines, pseudo-terminals, rlogin, RPC transparency | Unit 4 → "Remote Login & RPC Transparency" |
| Lab programs (sockets in C) | "Lab Practicals" lesson at the end |
Prerequisites
| You should know | Why |
|---|---|
C programming (pointers, structs, fork) | the entire API is C |
| TCP/IP basics: IP addresses, ports, the 3-way handshake | we now drive these from code |
| Basic Unix/Linux shell | compiling, running client+server in two terminals |
How to study this course
- Type and run every program. A Linux machine (or WSL on Windows) and
gccare all you need. One run of an echo server teaches more than three readings. - Keep two terminals open — client on the left, server on the right — and watch both sides of every experiment.
- Use the tools as you learn the calls:
netstat -an/ss -tanto see socket states,tcpdump/Wireshark to watch the segments your code generates. - Draw the call sequence for every program — the socket-function "ladder diagrams" in these lessons are the exact diagrams exam answers want.
- Memorise the failure-mode stories (Unit 2): what the client sees when the server crashes, vs reboots, vs is unreachable — favourite viva and theory questions.
What end-term questions in this paper look like
Network Programming questions come in four recognisable shapes — knowing the shape tells you how to structure the answer:
| Question shape | Example | What a full-marks answer contains |
|---|---|---|
| "Explain function X" | "Explain accept() with its arguments" | full prototype, each argument's role and direction, return value, one error case, 3–4 line code fragment |
| "Diagram + walkthrough" | "Explain TCP connection establishment" | the sequence/ladder diagram, segment names (SYN, SYN-ACK, ACK), which socket call blocks where, state names |
| "Compare A and B" | "Compare select and poll" / "TCP vs UDP" | a table of 5–7 rows, then 2–3 sentences saying when you'd choose which |
| "Scenario / what happens if" | "What does the client observe when the server host crashes?" | timeline of events on the wire, the errno the application finally sees, and the fix (timeout / keep-alive / select) |
Two writing habits that consistently earn marks: always give the prototype before discussing a function (examiners scan for it), and always name the errno in failure scenarios — "the call fails" earns half of what "connect returns −1 with errno ECONNREFUSED because an RST arrived" earns.
The vocabulary you must own before Unit 1
A quick glossary — every term below is defined properly in its lesson, but you should recognise them from day one:
- descriptor (fd): small integer naming an open file/socket in a process — the currency of the whole API.
- segment / datagram / frame: the protocol unit at TCP / UDP-IP / link layer respectively. Using the right word signals competence.
- well-known vs ephemeral port: server's fixed advertised port vs the kernel-chosen temporary client port.
- blocking call: one that puts the process to sleep until the event happens (default for accept, read, recvfrom...).
- half-close: closing one direction of a TCP connection while the other keeps flowing (
shutdown). - RST vs FIN: abortive reset vs orderly goodbye — the difference drives half of Unit 2's failure stories.
Self-check before you begin
- Which layer of the OSI model does the sockets API expose to your program, and which layers does your program itself implement?
- Name the three pieces of information that uniquely identify one end of a TCP connection, and the four that identify the whole connection.
- Why does a TCP application need two terminals (client + server) to test, while a UDP experiment can sometimes fake it with one?
- What tool shows you the TCP state (LISTEN, ESTABLISHED...) of every socket on your machine right now?
If question 2 made you pause — (IP, port) per end; (client IP, client port, server IP, server port) for the connection, the famous 4-tuple — you are exactly where this course expects you to start.
Unit 1: Protocol Foundations — OSI, Unix Standards, TCP & UDP
1.1 Where socket programs sit in the layer cake
OSI model what network programs see
7 Application ┐
6 Presentation │ ←── YOUR PROGRAM (all three top layers)
5 Session ┘
4 Transport ←── TCP / UDP — the SOCKETS API boundary
3 Network ←── IP (raw sockets reach here — Unit 4)
2 Data link ←── BPF / DLPI / SOCK_PACKET reach here — Unit 4
1 Physical
The sockets API is the door between the application process and the kernel's transport layer. Everything above the dotted line is your code; everything below runs in the kernel. The practical model is the 4-layer TCP/IP stack (application / transport / network / link) rather than the full 7-layer OSI.
1.2 Unix standards (know the names)
| Standard | What it is |
|---|---|
| POSIX (IEEE 1003) | the portable OS interface — defines the sockets functions we use |
| The Single UNIX Specification / XPG | The Open Group's superset; "UNIX certified" systems implement it |
| BSD heritage | sockets were born in 4.2BSD (1983); "Berkeley sockets" is still the API's name |
| SVR4 / TLI / XTI | System V's alternative transport interface — historical, lost to sockets |
Practical meaning: code written to POSIX sockets compiles on Linux, the BSDs, macOS, Solaris — and with the Winsock variant, Windows.
1.3 TCP vs UDP — the two transports you program against
| Property | TCP | UDP |
|---|---|---|
| Type | connection-oriented byte stream | connectionless datagrams |
| Reliability | acknowledgements, retransmission, no loss/dup | none — "best effort" |
| Ordering | guaranteed in-order | may reorder |
| Flow control | sliding window | none |
| Congestion control | yes | no |
| Message boundaries | not preserved (a stream!) | preserved (one sendto = one datagram) |
| Typical uses | HTTP, SSH, mail, file transfer | DNS, DHCP, SNMP, NTP, voice/video, games |
Two stream facts that bite programmers: a single write may arrive as several reads (and vice versa) — applications must impose their own message framing; and TCP is full-duplex — data flows both directions independently.
1.4 TCP connection establishment & termination (programmer's view)
Three-way handshake — and which socket calls trigger what:
Termination takes four segments (each direction closes independently): FIN → ACK → FIN → ACK. The end that closes first enters TIME_WAIT and stays there for 2·MSL (twice the maximum segment lifetime, typically 1–4 minutes total). Why TIME_WAIT exists — two reasons examiners want verbatim:
- to retransmit the final ACK if it is lost (reliable full-duplex close), and
- to let old duplicate segments die before the same (IP, port) pair is reused — protecting a new incarnation of the connection from ghosts of the old one.
TCP states you must recognise in netstat: LISTEN, SYN_SENT, SYN_RCVD, ESTABLISHED, FIN_WAIT_1/2, CLOSE_WAIT, LAST_ACK, TIME_WAIT, CLOSED.
Segment format essentials: source/destination ports (16 bits each), sequence & acknowledgement numbers (32 bits), flags (SYN, ACK, FIN, RST, PSH, URG), window (16 bits — flow control), checksum. UDP's header is just 8 bytes: ports, length, checksum.
1.5 Buffer sizes and limitations (frequent short-answer question)
| Quantity | Typical value / limit |
|---|---|
| IPv4 datagram max | 65,535 bytes (16-bit total-length field) |
| IPv4 minimum reassembly buffer | 576 bytes — the safe upper bound for application UDP datagrams |
| Ethernet MTU | 1500 bytes |
| MSS (max segment size) | MTU − 40 (IPv4: 20 IP + 20 TCP) ≈ 1460 |
| TCP send/receive socket buffers | kernel-dependent (e.g. 64 KB+), tunable via SO_SNDBUF / SO_RCVBUF |
| Path MTU | smallest MTU along the route; discovered via DF bit + ICMP |
A datagram larger than the MTU is fragmented by IP; TCP avoids fragmentation by never sending more than the MSS; UDP applications must size datagrams themselves — that's why DNS classically capped answers at 512 bytes.
1.6 Standard Internet services & protocol usage
Classic simple services (historically served by inetd — Unit 3): echo (7), discard (9), daytime (13), chargen (19), time (37). Well-known ports live in /etc/services: FTP 21, SSH 22, telnet 23, SMTP 25, DNS 53, HTTP 80, POP3 110, NTP 123, HTTPS 443. Port ranges: 0–1023 well-known (privileged), 1024–49151 registered, 49152–65535 ephemeral (the kernel assigns these to clients).
Protocol choice by application (the "protocol usage by common internet applications" table):
| Application | Transport | Why |
|---|---|---|
| HTTP/HTTPS, FTP, SMTP, SSH | TCP | needs reliability & streams |
| DNS | UDP (TCP fallback for big answers/zone transfers) | small request/response |
| DHCP, SNMP, TFTP | UDP | simplicity, broadcast needs |
| NTP/SNTP | UDP | timestamps hate retransmission delays |
| Voice/video (RTP), games | UDP | timeliness over reliability |
| Routing: RIP uses UDP, BGP uses TCP, OSPF rides raw IP | mixed | fit for purpose |
1.7 The TCP state transition diagram — a guided walkthrough
The state diagram is the single most-asked figure from this unit. Don't memorise it as a picture; memorise it as two journeys through the states:
Journey 1 — the client (active open):
CLOSED --connect(): send SYN--> SYN_SENT --recv SYN+ACK, send ACK--> ESTABLISHED
ESTABLISHED --close(): send FIN--> FIN_WAIT_1 --recv ACK--> FIN_WAIT_2
FIN_WAIT_2 --recv FIN, send ACK--> TIME_WAIT --2·MSL timer--> CLOSED
Journey 2 — the server (passive open):
CLOSED --listen()--> LISTEN --recv SYN, send SYN+ACK--> SYN_RCVD
SYN_RCVD --recv ACK--> ESTABLISHED
ESTABLISHED --recv FIN, send ACK--> CLOSE_WAIT (application still has the socket open!)
CLOSE_WAIT --close(): send FIN--> LAST_ACK --recv ACK--> CLOSED
Three observations that turn a description into a full-marks answer:
- The active closer takes the TIME_WAIT branch; the passive closer takes the CLOSE_WAIT → LAST_ACK branch. Whichever end calls close first pays the 2·MSL penalty — which is why well-designed protocols often arrange for the client to close first (servers can't afford thousands of TIME_WAIT slots... though busy web servers suffer exactly this).
- **CLOSE_WAIT means "the peer has finished; your application hasn't called close yet".** A server stuck with growing CLOSE_WAIT counts in
netstathas a descriptor leak — it never noticed read() returning 0. This is a real-world debugging heuristic worth quoting. - Simultaneous open and simultaneous close exist (both ends SYN, or both FIN, at once) — rare paths through SYN_RCVD and CLOSING, worth one sentence in a long answer to show you've seen the full diagram.
1.8 Flow control vs congestion control — don't conflate them
Students lose marks by treating these as synonyms. They solve different problems with different mechanisms:
| Aspect | Flow control | **Con
Frequently asked questions
Is the Network Programming course really free?
Yes. The entire Network Programming course on Siksha Sarovar is free to read with no account required. You can optionally sign in with Google to save your progress.
Do I get a certificate for Network Programming?
Yes — finish the lessons and pass the quiz to earn a free, verifiable certificate you can share on LinkedIn or with recruiters.
Can I run code while learning?
Yes. The built-in online compiler runs C, C++, Python, Java, PHP, JavaScript, C# and SQL directly in your browser — no installation needed.