A socket is a program's endpoint for network I/O. Learn the Berkeley sockets API for TCP — server and client call order, address structures, byte order, iterative versus concurrent servers, Java's Socket classes — and the TELNET and HTTP protocols that run over it.
Medium 60 minSyllabus: “Sockets programming: TCP programming (TELNET, HTTP)”
Mark as
The idea in one minute
Think of an office switchboard. The server is the receptionist: she gets a phone (socket), is given an extension number (bind), switches on call-taking (listen), and answers each ringing call (accept) — which gives her a fresh line for that caller while the main number stays free for others. The client just dials the number (connect). Once connected, both sides read and write as if the line were a file, and hanging up (close) tells the other side the conversation is over.
Key points — the night-before list
A socket is a communication endpoint, returned as a file descriptor by socket(family, type, protocol): SOCK_STREAM = TCP, SOCK_DGRAM = UDP. The BSD sockets API dates from 4.2BSD (1983).
listen() makes the socket passive and sets the backlog; the kernel completes the three-way handshake; accept() returns a new connected descriptor while the listening socket keeps waiting.
struct sockaddr_in holds sin_family = AF_INET (host order) plus sin_port and sin_addr in network byte order (big-endian): htons for ports, htonl for addresses, inet_pton for dotted text.
Iterative servers serve one client at a time; concurrent servers fork() or start a thread per client, or multiplex with select(). Java: ServerSocket (backlog 50) → accept() → Socket.
Address already in use comes from bind() (port busy or TIME_WAIT — set SO_REUSEADDR); Connection refused from connect() means an RST: host up, nothing listening.
TELNET (TCP 23): Network Virtual Terminal, in-band commands after IAC (255), options negotiated with WILL 251, WONT 252, DO 253, DONT 254; plain text, so replaced by SSH (22).
HTTP (TCP 80) is text: request line, headers, an empty line (each ending CR LF), optional body; replies open with a status line like HTTP/1.1 200 OK.
01Sockets and the client–server model
Application programs never handle network cards or TCP segments themselves. They ask the operating system for a socket — an endpoint for communication — and read and write through it. On Unix a socket is a small integer file descriptor, the same kind of handle that open() returns for a file, so read(), write() and close() work on it too. Underneath, the kernel's TCP/IP code does all the segmenting, acknowledging and retransmitting.
The interface used almost everywhere is the Berkeley sockets API (BSD sockets), introduced with 4.2BSD Unix from the University of California, Berkeley, in 1983. POSIX standardised it, Windows copies it as Winsock, and Java, Python and C# wrap it in classes — learn it once in C and every other socket library looks familiar.
Network programs follow the client–server model. The server starts first, attaches itself to a fixed, published port (23 for TELNET, 80 for HTTP) and waits. A client starts whenever a user needs it, contacts the server's IP address and port, and gets a temporary ephemeral port from its own kernel. A TCP connection is identified by the 4-tuple (client IP, client port, server IP, server port), which is how one server port can carry thousands of conversations at once.
Argument
Common values
Meaning
family (domain)
AF_INET, AF_INET6, AF_UNIX (also AF_LOCAL)
IPv4, IPv6, or local communication between processes on one machine
type
SOCK_STREAM
Reliable, connection-oriented byte stream → TCP
type
SOCK_DGRAM
Connectionless datagrams with boundaries → UDP
type
SOCK_RAW
Direct access to IP, as used by ping for ICMP; needs superuser rights
protocol
0, or IPPROTO_TCP / IPPROTO_UDP
0 selects the default protocol for that family and type
int socket(int family, int type, int protocol) returns a descriptor ≥ 0, or −1 with errno set
PSC favourite
'A socket address is' → IP address + port number. 'Socket type for TCP' → SOCK_STREAM; for UDP → SOCK_DGRAM. socket() only creates the endpoint — no packet is sent until connect() or a send call.
02Socket addresses and network byte order
Every socket call that needs an address takes a pointer to a socket address structure. For IPv4 it is struct sockaddr_in from <netinet/in.h>. Because the same calls also accept IPv6 and Unix-domain addresses, their prototypes use the generic struct sockaddr *, so you fill a sockaddr_in and cast its address when calling bind(), connect() or accept().
CThe IPv4 socket address (POSIX layout; BSD systems add a leading sin_len byte — still 16 bytes in all)
A multi-byte number can be stored most-significant byte first (big-endian) or least-significant byte first (little-endian). Intel x86 and most ARM systems are little-endian, but every TCP/IP header field is defined as big-endian — network byte order. So ports and IPv4 addresses placed in a socket address structure must be converted from host order to network order with the functions below (declared in <arpa/inet.h>).
Function
Converts
Typical use
htons(x)
host → network, 16-bit (short)
A port number going into sin_port
htonl(x)
host → network, 32-bit (long)
A numeric IPv4 address such as INADDR_ANY or INADDR_LOOPBACK
ntohs(x)
network → host, 16-bit
Printing the port of an address returned by accept() or recvfrom()
ntohl(x)
network → host, 32-bit
Arithmetic on a received IPv4 address
inet_pton(AF_INET, str, &addr)
dotted text → 32-bit binary, already in network order
Filling sin_addr from text such as 192.168.1.5; returns 1 = success, 0 = malformed text, −1 = bad family
inet_ntop(AF_INET, &addr, buf, len)
binary → dotted text
Logging a client's address; use buffers of INET_ADDRSTRLEN (16) or INET6_ADDRSTRLEN (46) bytes
Port 8080 = 0x1F90
big-endian memory (network order): 1F 90
little-endian memory (x86 order): 90 1F
htons(8080) on x86 returns 0x901F, which sits in memory as 1F 90 — network order.
On a big-endian host htons() and htonl() do nothing.
IPv4 192.168.1.10 in network order: C0 A8 01 0A
Why the conversion matters
Watch out
Forget htons() on an x86 PC and sin_port = 8080 leaves bytes 90 1F in memory, which the network reads as port 0x901F = 36895. The opposite mistake is just as common: inet_pton() and inet_addr() already return network order, so wrapping them in htonl() scrambles the address. Both bugs stay hidden on big-endian machines, where the conversions do nothing.
Tip
Read the names aloud: host tonetwork short. 's' = 16 bits (ports), 'l' = 32 bits (IPv4 addresses). In inet_pton, 'p' is presentation (text) and 'n' is numeric. Prefer inet_pton()/inet_ntop() and getaddrinfo() to the old IPv4-only inet_addr(), inet_ntoa() and gethostbyname().
03The TCP call sequence, step by step
A TCP server and client make a fixed series of calls. Picture two columns that meet at the handshake: the server prepares and waits, the client connects, both exchange data, and one side closes. The table after the steps shows what TCP is doing underneath each call.
TCP server
socket(AF_INET, SOCK_STREAM, 0)
Create the endpoint and get the listening descriptor. Nothing is sent on the network yet.
bind(fd, &servaddr, len)
Attach a local address: the server's well-known port, usually with INADDR_ANY so that connections arriving on any local interface match.
listen(fd, backlog)
Turn the socket from active to passive (TCP state CLOSED → LISTEN) and size the queue of pending connections. listen() returns at once — it never blocks.
accept(fd, &cliaddr, &len)
Sleep until a connection has completed the three-way handshake, then return a new connected descriptor and the client's address. The listening socket stays open for the next client.
recv() / send()
Exchange bytes on the connected descriptor (read() and write() work too). recv() returns 0 when the client has closed its side.
close(connfd)
End this connection (TCP sends FIN) and loop back to accept().
TCP client
socket(AF_INET, SOCK_STREAM, 0)
Create the endpoint. A client normally skips bind().
connect(fd, &servaddr, len)
Fill a sockaddr_in with the server's IP and port and connect: the kernel picks an ephemeral port, sends SYN and blocks until the handshake succeeds or fails.
send() / recv()
Write the request, read the reply.
close(fd)
Send FIN. Whichever side closes first passes through TIME_WAIT for 2 MSL.
Call
Blocks?
What TCP does
socket()
No
Allocates the socket; state CLOSED
bind()
No
Records the local IP and port; fails with EADDRINUSE if they are taken
listen()
No
State LISTEN: from now on the kernel answers SYNs with SYN+ACK by itself
connect()
Yes, about one RTT
Sends SYN (SYN_SENT); returns once SYN+ACK arrives and the final ACK is sent (ESTABLISHED)
accept()
Yes, until a connection is ready
Takes the first completed connection off the queue; accept() itself exchanges no packets
recv()
Yes, until data, FIN or an error
Copies bytes out of the receive buffer; 0 means a FIN was received
send()
Only while the send buffer is full
Copies bytes into the send buffer; TCP segments and transmits them later
shutdown(fd, SHUT_WR)
No
Sends FIN at once — a half-close: this side can still receive
close()
No (by default)
Sends FIN once the socket's reference count drops to 0
The backlog passed to listen() bounds two kernel queues: the incomplete queue (SYN received, handshake in progress — SYN_RCVD) and the completed queue (ESTABLISHED, waiting for accept()). Historically the backlog covered both; Linux applies it to the completed queue only. When the queues are full, most Unix kernels silently ignore new SYNs, so clients retransmit and usually get in a moment later instead of being refused.
PSC favourite
The three-way handshake is completed by the kernel, not by accept(): accept() only hands over a connection that is already ESTABLISHED. listen() and accept() are server-only calls, connect() is the client's call, and accept() returns a new descriptor while the listening one stays open.
04A complete echo server and client in C
The classic first network program is an echo service: the client sends lines of text and the server returns them unchanged (the standard echo service, RFC 862, even has its own port, 7). The server below is concurrent — it fork()s a child for each client, so one slow user cannot hold up the others. It uses port 9877, the port used throughout Stevens' UNIX Network Programming.
Cecho_server.c — concurrent TCP echo server (build: cc -o echo_server echo_server.c)
/* echo_server.c — concurrent TCP echo server: one child process per client */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <signal.h>#include <unistd.h>#include <sys/wait.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#define SERV_PORT 9877#define BACKLOG 16
static void reap_children(int signo) { /* SIGCHLD handler: no zombies */
(void) signo;
while (waitpid(-1, NULL, WNOHANG) > 0)
;
}
static int send_all(int fd, const char *p, size_t len) { /* send() may write only part */
while (len > 0) {
ssize_t n = send(fd, p, len, 0);
if (n < 0) {
if (errno == EINTR) continue;
return -1;
}
p += n;
len -= (size_t) n;
}
return 0;
}
static void echo(int connfd) { /* return every byte until the client closes */
char buf[4096];
ssize_t n;
while ((n = recv(connfd, buf, sizeof buf, 0)) > 0)
if (send_all(connfd, buf, (size_t) n) < 0)
break;
}
int main(void) {
int listenfd, connfd, on = 1;
struct sockaddr_in servaddr, cliaddr;
socklen_t clilen;
char ip[INET_ADDRSTRLEN];
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); }
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on); /* restart without EADDRINUSE */
memset(&servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof servaddr) < 0) { perror("bind"); exit(1); }
if (listen(listenfd, BACKLOG) < 0) { perror("listen"); exit(1); }
signal(SIGCHLD, reap_children);
for (;;) {
clilen = sizeof cliaddr; /* value-result argument: reset each time */
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
if (connfd < 0) {
if (errno == EINTR) continue; /* interrupted by SIGCHLD: just retry */
perror("accept");
exit(1);
}
fprintf(stderr, "client %s:%d\n",
inet_ntop(AF_INET, &cliaddr.sin_addr, ip, sizeof ip), ntohs(cliaddr.sin_port));
if (fork() == 0) { /* child */
close(listenfd); /* the child never accepts */
echo(connfd);
close(connfd); /* FIN to the client */
exit(0);
}
close(connfd); /* parent: the child owns this connection */
}
}
Cecho_client.c — run as ./echo_client 127.0.0.1
/* echo_client.c — send each line typed on stdin and print the server's echo */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#define SERV_PORT 9877
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in servaddr;
char line[4096], reply[4097];
ssize_t n;
if (argc != 2) { fprintf(stderr, "usage: %s server-IPv4-address\n", argv[0]); exit(1); }
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); }
memset(&servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) != 1) { /* text → binary */
fprintf(stderr, "not an IPv4 address: %s\n", argv[1]);
exit(1);
}
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof servaddr) < 0) {
perror("connect"); /* e.g. "connect: Connection refused" */
exit(1);
}
while (fgets(line, sizeof line, stdin) != NULL) {
send(sockfd, line, strlen(line), 0);
n = recv(sockfd, reply, sizeof reply - 1, 0); /* may hold only part of the line */
if (n <= 0) {
fputs(n == 0 ? "server closed the connection\n" : "recv failed\n", stderr);
break;
}
reply[n] = '\0';
fputs(reply, stdout);
}
close(sockfd); /* FIN: the server's recv() returns 0 */
return 0;
}
Two details matter. First, TCP is a byte stream with no message boundaries: a 2,000-byte send() may arrive as several recv() results, and send() may accept fewer bytes than asked — hence the loop in send_all(). The client's single recv() per line is a classroom simplification; real code loops until it has a whole line (Stevens' readn() and readline()). Second, recv() returning 0 is end-of-file: the peer has closed its side, so the loop ends and the socket is closed.
Message (errno)
From
Usual cause
Fix
Address already in use (EADDRINUSE)
bind()
Another process owns the port, or the server's previous run left connections in TIME_WAIT
Stop the other process; set SO_REUSEADDR before bind(), as the server above does
Permission denied (EACCES)
bind()
A port below 1024 without superuser rights
Use a port ≥ 1024 or run with privileges
Connection refused (ECONNREFUSED)
connect()
The host is up but nothing listens on that port, so its TCP answered the SYN with RST
Start the server; check the port number and its byte order
Connection timed out (ETIMEDOUT)
connect()
No reply to repeated SYNs — host down, wrong address, or a firewall dropping packets (75 s on 4.4BSD)
Check the address, routing and firewall rules
No route to host (EHOSTUNREACH)
connect()
A router sent back ICMP destination unreachable
Check routing and the address
Connection reset by peer (ECONNRESET)
recv(), send()
The peer aborted with RST — it crashed, or closed with unread data
Treat the connection as lost; reconnect if needed
Broken pipe (EPIPE + SIGPIPE)
send(), write()
Writing after the peer reset the connection; SIGPIPE kills the process by default
Ignore or catch SIGPIPE and check send()'s return value
Errors you will meet (errno names; Java's matching exceptions are in the next sections)
Tip
You can test any line-based TCP server without writing a client: nc 127.0.0.1 9877 or telnet 127.0.0.1 9877 connects and sends whatever you type. ss -tln on Linux (or netstat -an) lists listening sockets — the first thing to check after Address already in use or Connection refused.
05Iterative and concurrent servers
An iterative server serves one client completely, then loops back to accept() the next. It is simple and fine when every request takes a few milliseconds (a time-of-day service), but all other clients wait in the listen queue meanwhile. A concurrent server works on many clients at once; most TCP servers are concurrent.
Iterative server
One client at a time: accept → serve → close → accept
No processes or threads to manage, no shared-state bugs
A slow or idle client blocks everyone queued behind it
Suits short, fixed-time requests; most UDP servers work this way
Concurrent server
Many clients at once: a process, thread or event handler per connection
More to manage: reaping children, locking shared data, resource limits
A slow client delays only its own handler
Normal for TCP services — web, mail, SSH, databases
In the fork-per-client design used above, fork() duplicates the process, so parent and child both hold listenfd and connfd, and each socket's reference count becomes 2. The parent closes connfd and the child closes listenfd, leaving one owner for each. Since close() sends FIN only when the count reaches 0, a parent that forgets close(connfd) never lets connections end and leaks a descriptor per client. Finished children stay zombies until the parent reaps them with waitpid() in a SIGCHLD handler, and a signal arriving while accept() is blocked can make it fail with EINTR — so the loop retries.
Design
How it works
Trade-off
Iterative
One loop: accept, serve, close
Simplest; clients queue up
Process per client (fork)
The parent accepts; a child serves each connection
Strong isolation; fork costs time and memory
Thread per client (pthread_create, Java Thread)
A new thread serves each connected socket
Cheaper than fork; shared data needs locks
Pre-forked processes / thread pool
Workers created in advance take turns at accept() or a job queue
No start-up cost per client; the pool size caps concurrency
I/O multiplexing (select, poll, epoll, kqueue)
One process waits on many descriptors and serves whichever is ready
Handles thousands of mostly idle connections; the code becomes an event loop (nginx, Node.js)
select(maxfd + 1, &readset, &writeset, &exceptset, &timeout) sleeps until at least one descriptor in the sets is ready or the timeout expires, then reports which. A listening socket becomes readable when a completed connection is waiting for accept(); a connected socket becomes readable when data or a FIN has arrived. The sets are manipulated with FD_ZERO, FD_SET, FD_CLR and FD_ISSET, and their size is limited by FD_SETSIZE (usually 1,024).
PSC favourite
'A single process serving many clients at once' → I/O multiplexing with select()/poll(). In the fork model the parent closes the connected socket and the child closes the listening socket.
06The same in Java: ServerSocket and Socket
Java's java.net package wraps the C calls in two classes. A ServerSocket is the listening socket: its constructor performs socket(), bind() and listen() together (default backlog 50), and its accept() blocks and returns a Socket — the connected socket. A client writes new Socket(host, port), which resolves the name, creates the socket and connects in one step. Data then flows through ordinary streams from getInputStream() and getOutputStream().
JavaEchoServer.java — one thread per client
import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
try (ServerSocket listener = new ServerSocket(9877)) { // socket + bind + listen
while (true) {
Socket client = listener.accept(); // blocks until a client connects
new Thread(() -> serve(client)).start(); // concurrent: a thread per client
}
}
}
private static void serve(Socket s) {
try (s;
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true)) { // true = auto-flush
String line;
while ((line = in.readLine()) != null) // null: the client closed its side
out.println(line); // echo it back
} catch (IOException e) {
System.err.println("client error: " + e.getMessage());
}
}
}
JavaEchoClient.java — run as java EchoClient 127.0.0.1
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
String host = args.length > 0 ? args[0] : "127.0.0.1";
try (Socket s = new Socket(host, 9877); // socket + connect
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = keyboard.readLine()) != null) {
out.println(line); // send
System.out.println("echo: " + in.readLine()); // receive
}
} // closing s sends FIN
}
}
C sockets API
Java (java.net)
socket() + bind() + listen()
new ServerSocket(port) or new ServerSocket(port, backlog)
accept()
serverSocket.accept(), which returns a Socket
socket() + connect()
new Socket(host, port)
recv() / send()
getInputStream() / getOutputStream(), usually wrapped in BufferedReader and PrintWriter
close()
close(), or let try-with-resources do it
SO_REUSEADDR, SO_RCVTIMEO options
setReuseAddress(true), setSoTimeout(ms)
ECONNREFUSED, EADDRINUSE, a timeout
ConnectException, BindException, SocketTimeoutException; an unknown host name gives UnknownHostException
Watch out
Create the writer as new PrintWriter(out, true) (auto-flush) or call flush(): output stuck in a buffer looks exactly like a hung server. And readLine() returning null is Java's version of recv() returning 0 — the peer has closed the connection.
07TELNET: remote login over one TCP connection
TELNET (RFC 854, 1983) lets a user at one computer log in to another and work there as if the keyboard and screen were attached directly. The client connects to TCP port 23; the server (telnetd) starts a login session and relays bytes between the connection and that session. Everything — data and control — travels over this single connection.
Computers once had wildly different terminals, so TELNET defines an imaginary standard one, the Network Virtual Terminal (NVT). Each client translates its local keyboard and screen to NVT form, and each server translates NVT to its own conventions, so neither side needs to know the other's terminal. NVT data is 7-bit US-ASCII carried in 8-bit bytes with the high bit 0; every line ends with CR LF, and a bare carriage return is sent as CR NUL.
Control information is mixed into the same byte stream — in-band signalling, unlike FTP, which keeps a separate control connection. The byte 255, IAC (Interpret As Command), announces that the next byte is a command rather than data. To send a real data byte 255, the sender doubles it: IAC IAC.
Code
Name
Meaning
255
IAC
Interpret As Command — the escape byte before every command
254
DONT
Please do not use (or stop using) the option
253
DO
Please use the option — or: I accept your offer
252
WONT
I will not use (or will stop using) the option
251
WILL
I will use the option — or: I agree to your request
250 / 240
SB / SE
Begin / end sub-negotiation of an option's parameters, such as the terminal type
244, 245, 246
IP, AO, AYT
Interrupt Process, Abort Output, Are You There
247, 248
EC, EL
Erase Character, Erase Line
249, 241
GA, NOP
Go Ahead (half-duplex turn-taking), No Operation
Sender says
Meaning
Agree
Refuse
WILL x
I offer to enable option x on my side
DO x
DONT x
DO x
I ask you to enable option x on your side
WILL x
WONT x
WONT x
I will not use x, or am switching it off
DONT x (must be accepted)
—
DONT x
Do not use x, or switch it off
WONT x (must be accepted)
—
Option negotiation: a request to disable can never be refused
Because disabling is always allowed, both sides can fall back to the plain NVT. Common options are ECHO (1), SUPPRESS-GO-AHEAD (3), TERMINAL-TYPE (24), NAWS — window size (31) — and LINEMODE (34). Forouzan lists three modes: default mode (the client echoes keystrokes and sends whole lines), character mode (every keystroke is sent and the server echoes it — negotiated with WILL ECHO and WILL SUPPRESS-GO-AHEAD) and line mode (the client edits each line locally and sends it complete).
Watch out
TELNET has no encryption: the user name, the password and every command cross the network as plain text that anyone capturing packets can read. For remote login it has been replaced by SSH (TCP port 22). The telnet client survives as a debugging tool because it opens a raw TCP connection to any port — telnet example.com 80 lets you type an HTTP request by hand.
08HTTP: a text protocol over TCP
HTTP (HyperText Transfer Protocol) is the Web's request–response protocol; versions 1.0 and 1.1 are plain text over TCP port 80. The client connects, writes a request message and reads a response message. Each message is a start line, zero or more header lines, an empty line and an optional body — and every line ends with the two bytes CR LF (\r\n).
TextA request and its response as they cross the socket
GET /index.html HTTP/1.1\r\n ← request line: method, target, version
Host: www.example.com\r\n ← one "Name: value" header per line
User-Agent: sockdemo/1.0\r\n
Connection: close\r\n
\r\n ← empty line: end of the headers
HTTP/1.1 200 OK\r\n ← status line: version, code, reason phrase
Date: Thu, 03 Dec 2026 10:00:00 GMT\r\n
Content-Type: text/html; charset=UTF-8\r\n
Content-Length: 1256\r\n ← exactly 1,256 body bytes follow
\r\n
<!doctype html><html> … </html> ← the body
Chttp_get.c — an HTTP client is just a TCP client that writes text
/* http_get.c — fetch a page with a hand-written HTTP/1.1 request.
usage: ./http_get example.com / */#include <stdio.h>#include <string.h>#include <unistd.h>#include <netdb.h>#include <sys/socket.h>
int main(int argc, char *argv[]) {
struct addrinfo hints, *res;
char req[1024], buf[4096];
int fd, err, len;
ssize_t n;
if (argc != 3) { fprintf(stderr, "usage: %s host path\n", argv[0]); return 1; }
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /* IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP */
if ((err = getaddrinfo(argv[1], "80", &hints, &res)) != 0) { /* DNS lookup + port 80 */
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
return 1;
}
fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (fd < 0 || connect(fd, res->ai_addr, res->ai_addrlen) < 0) { perror("connect"); return 1; }
freeaddrinfo(res);
len = snprintf(req, sizeof req,
"GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"\r\n", /* the empty line ends the headers */
argv[2], argv[1]);
if (len < 0 || len >= (int) sizeof req) { fputs("request too long\n", stderr); return 1; }
send(fd, req, (size_t) len, 0);
while ((n = recv(fd, buf, sizeof buf, 0)) > 0) /* until the server closes: recv() = 0 */
fwrite(buf, 1, (size_t) n, stdout);
close(fd);
return 0;
}
The client finds the end of the body from Content-Length, from Transfer-Encoding: chunked (the body arrives as length-prefixed chunks), or — as here, with Connection: close — because the server closes the connection and recv() returns 0. HTTP/1.1 makes the Host header mandatory (one IP address may serve many sites) and keeps connections persistent by default, so several requests reuse one TCP connection; HTTP/1.0 opened a new connection for every object.
Version
Year / specification
Transport and key change
HTTP/0.9
1991
A single line GET /path; HTML only, no headers
HTTP/1.0
1996, RFC 1945
Headers, status codes, content types; one TCP connection per object by default
HTTP/1.1
1997 (RFC 2068), 1999 (RFC 2616); now RFC 9112 (2022)
Binary frames; many streams multiplexed on one TCP connection; header compression
HTTP/3
2022, RFC 9114
Runs over QUIC on UDP port 443
PSC favourite
Status-code classes: 1xx informational, 2xx success (200 OK), 3xx redirection (301, 304), 4xx client error (400, 403, 404), 5xx server error (500, 503). Methods, headers and cookies are covered in Module 6's HTTP topic; the point here is that HTTP is just text written to a TCP socket, which is why a request can be typed by hand in a telnet example.com 80 session.
Step through · A TCP echo session: the API calls on each side
step 1 / 11
Step 1: socket() → listenfd = 3
The server asks the kernel for a TCP endpoint with socket(AF_INET, SOCK_STREAM, 0). Nothing is sent on the network yet.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Byte order: what really goes on the wire
A client on an x86 (little-endian) PC sets servaddr.sin_port = 8080; and servaddr.sin_addr.s_addr = htonl(inet_addr("10.0.0.1"));, then calls connect(). Which address and port does it actually try to reach, and how should the two lines be written?
EX 2Tracing descriptors through fork() in a concurrent server
In the concurrent echo server, listenfd = 3. A client connects and accept() returns connfd = 4. Trace each socket's reference count through fork() and the close() calls. What goes wrong if the parent omits close(connfd)?
EX 3Counting round trips: non-persistent vs persistent HTTP
A page consists of one HTML file and 10 small images on the same server. RTT = 50 ms and transmission times are negligible. How long does fetching everything take with (a) non-persistent HTTP, one connection at a time; (b) persistent HTTP without pipelining; (c) persistent HTTP with pipelining; (d) non-persistent HTTP with up to 10 parallel connections?
EX 4Decoding a TELNET option negotiation
Right after connecting to port 23, a client receives the bytes FF FD 18 FF FD 1F FF FB 01 FF FB 03 (hex). Decode them, and give the replies of a client that supports all four options.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write, byte for byte, the HTTP/1.1 request that fetches /index.html from www.example.com and asks the server to close the connection afterwards. How many bytes does it contain?
Q2
Give the most likely cause of each failure: (a) a server restarted a few seconds after being stopped fails in bind() with Address already in use; (b) a client's connect() fails instantly with Connection refused; (c) a client's connect() hangs for over a minute, then fails with Connection timed out; (d) a server started by an ordinary user fails in bind() for port 80 with Permission denied.
Q3
Five clients connect at the same moment to a server that spends 200 ms serving each one, mostly waiting for a disk and a database. When does the last client finish, and what is the average completion time, with (a) an iterative server and (b) a fork-per-client concurrent server? Assume the CPU is never the bottleneck.
Q4
A student's TCP server calls socket(), listen() and accept() but forgets bind(). Clients connecting to port 9877 get Connection refused. Explain, and say where the server is really listening. Why is skipping bind() normal for a client?
Q5
In a TELNET session where BINARY transmission (option 0) is in effect, a client must send the four data bytes 41 FF 0D 0A (hex). What goes on the wire, and why? How does a client that does not support line mode answer IAC DO LINEMODE?
Exam traps
accept() does not perform the three-way handshake: the kernel completes it once listen() has been called, and accept() only dequeues an ESTABLISHED connection and returns a new descriptor. listen() never blocks.
htons/ntohs are for 16-bit ports, htonl/ntohl for 32-bit IPv4 addresses. inet_pton() and inet_addr() already produce network order — wrapping them in htonl() breaks the address on little-endian machines.
A TCP client normally does not call bind() (the kernel picks an ephemeral port at connect()), and it never calls listen() or accept().
TCP has no message boundaries: one send() may need several recv() calls and vice versa. recv() returning 0 means the peer closed (end of file); −1 means an error.
Connection refused = an RST came back (host up, nothing listening); Connection timed out = no reply at all. Address already in use comes from bind(), not from connect().
TELNET uses one TCP connection (port 23) with in-band IAC commands; FTP uses two (21 control, 20 data). Forouzan expands TELNET as TErminaL NETwork; other sources say teletype network.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.