Part ofSystems Programming Companion, week 12
Introduction to Sockets
Networking in C boils down to sockets: the abstraction the kernel hands you for shovelling bytes across a network. Web servers, chat apps, multiplayer games — they're all sockets dressed up.
What Is a Socket?
A socket is a file descriptor sitting at one end of a network connection. The same way you read() and write() files, you send() and recv() over a socket.
#include <sys/socket.h>
int sockfd = socket(AF_INET, SOCK_STREAM, 0);The three arguments specify:
AF_INET- use IPv4 addressingSOCK_STREAM- use TCP (reliable, ordered byte stream)0- let the OS choose the default protocol
Sockets follow the Unix philosophy: everything is a file. A socket file descriptor works with many of the same system calls you use for files, which is why C's low-level I/O model maps so naturally to network programming.
The Socket Address Structure
To connect to a remote host, you need an address. In C, addresses are represented by struct sockaddr_in:
#include <netinet/in.h>#include <arpa/inet.h>
struct sockaddr_in addr;addr.sin_family = AF_INET;addr.sin_port = htons(8080);if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) != 1) { fprintf(stderr, "not a valid IPv4 address\n"); return 1;}htons()converts the port number from host byte order to network byte order (big-endian).inet_pton()converts a dotted-decimal IP string into the 32-bit network-order address. It returns 1 on success, 0 if the string isn't a valid address, and -1 if the address family is wrong, so you can tell bad input apart. You'll still see the olderinet_addr()in tutorials. Avoid it: it signals failure by returningINADDR_NONE, which is the same value as the perfectly valid address 255.255.255.255.
TCP vs UDP
| Feature | TCP (SOCK_STREAM) | UDP (SOCK_DGRAM) |
|---|---|---|
| Reliability | Guaranteed delivery | Best-effort |
| Ordering | In-order delivery | No ordering |
| Connection | Connection-oriented | Connectionless |
| Use case | HTTP, SSH, databases | DNS, video streaming |
This module sticks with TCP. It's what most application protocols are built on.
The Lifecycle of a TCP Connection
- Create a socket with
socket() - Connect to a server with
connect()(client) or bind + listen + accept (server) - Send/Receive data with
send()/recv() - Close the connection with
close()
Here's how the two sides line up in time. The handshake happens inside connect() and the server's kernel; neither program sends those packets by hand. accept() just collects a connection the kernel has already finished setting up.
Next lessons walk through both sides of that lifecycle.