Networking in C · intermediate · ~10 min
Understand the BSD sockets API.
A socket is the file-descriptor-like endpoint for network communication. The same syscalls (socket, bind, listen, accept, connect, read, write, close) handle TCP, UDP, Unix domain sockets, and more — just by varying the address family and protocol.
Every networked application — web server, database client, chat program, IoT device — uses sockets underneath. Languages like Python and Go wrap the same Berkeley API. Learn C sockets and you understand the API behind every framework you'll ever use.
Address family. AF_INET (IPv4), AF_INET6, AF_UNIX. Type. SOCK_STREAM (TCP — reliable byte stream), SOCK_DGRAM (UDP — best-effort datagrams). Endianness. Network byte order is big-endian; use htons, htonl, ntohs, ntohl to convert. Localhost only. This course's labs all bind to 127.0.0.1 for safety.
#include <sys/socket.h>
#include <netinet/in.h>
int s = socket(AF_INET, SOCK_STREAM, 0); // TCP socket
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(8080),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK), // 127.0.0.1
};
bind(s, (struct sockaddr *)&addr, sizeof addr);
listen(s, 16);
A socket is a file descriptor for network I/O. The BSD sockets API is the C standard since the early 80s: socket() creates one, bind() ties it to an address, listen()/accept() wait for incoming connections, connect() reaches out.
SOCK_STREAM is TCP — reliable, ordered bytes. SOCK_DGRAM is UDP — packets, possibly lost or reordered.
#include <sys/socket.h>
int s = socket(AF_INET, SOCK_STREAM, 0);
ss -tlnp lists every TCP listener with its PID — confirms your server actually opened the port. nc 127.0.0.1 8080 is a quick client to test handshakes. Common error 'Address already in use' means a previous run is still holding the port (use SO_REUSEADDR).
Sockets are file descriptors — same leak class. Close on every error path. Buffers from recv are not null-terminated; treat them as (data, length) pairs. Never trust the byte count — caps and bounds matter.
HTTP servers, REST/gRPC clients, database protocols (Postgres, MySQL wire), every messaging app, OS network managers.
nc. 3. Echo whatever you read back to the client.Sockets are the universal Unix networking abstraction. Same syscalls handle every transport. Bind to localhost for safety, use network byte order for port numbers, and close every socket. From here you can build any client or server.