Skip to content

38. IPC — Sockets

A socket is a communication endpoint — the only IPC mechanism that works across a network (and can also be used locally).

Stream sockets (TCP): connection-oriented, reliable, ordered — like a phone call. Used for HTTP, SSH, databases. Datagram sockets (UDP): connectionless, unreliable, unordered — like sending a postcard. Used for DNS, video, gaming, VoIP.

TCP 3-way handshake: SYN (client→server, "I want to connect") → SYN-ACK (server→client, "OK, acknowledged") → ACK (client→server, "connected").

Socket domains: AF_INET/AF_INET6 for network communication (IP + port); AF_UNIX for same-machine-only IPC, faster than TCP since it skips the network stack (used between nginx and PHP-FPM, or for the Docker daemon socket).

TCP UDP
ConnectionRequiredNot required
ReliabilityGuaranteedBest effort
OrderingIn orderMay reorder
SpeedSlowerFaster
Use caseHTTP, SSH, DBDNS, video, gaming

Blocking vs non-blocking sockets: blocking read() waits for data; non-blocking returns immediately with EAGAIN if none is ready, needing an event loop. epoll (Linux) scales this to thousands of connections by telling you which sockets are ready in O(1), rather than scanning all of them like select/poll — this is the basis of Nginx's and Node.js's event loops.