Sockets & Ports
The problem
A single machine can run many programs that each need to communicate over a network, and the network needs a way to deliver incoming data to the right program on the right machine — sockets and ports are the addressing scheme that makes that delivery possible.
Why now
Interprocess communication already introduced sockets as the cross-machine generalization of same-machine pipes; this topic makes that generalization concrete, adding the specific addressing scheme (IP address plus port number) that lets data find not just the right machine but the right program on it.
Mental model
An IP address is a building's street address; a port number is the specific apartment. A socket is the open connection endpoint a program creates at one apartment number, through which all its network conversation flows — created with the same kind of system call as opening a file, because to the OS, a socket is just another kind of file descriptor.
Requires
- Interprocess CommunicationOperating Systems
A network socket is the cross-machine generalization of the local IPC socket already introduced there; the connection-oriented, bidirectional-channel model transfers directly.
- System Calls & the KernelOperating Systems
Creating and using a socket (socket(), bind(), connect()) is done through system calls, mediated by the kernel exactly like file I/O — you need the system call concept for 'opening a socket' to mean something concrete.
Unlocks
Used in
- Every network client and server program (a web server listens on a socket bound to port 80/443)
- WebSockets — a persistent bidirectional socket connection over HTTP
- Port scanning and firewall rules (allowing/blocking specific ports)
- Local development servers (localhost:3000 names a port on your own machine)
Projects
- Write a minimal TCP server that listens on a port and echoes back anything a client sends, then connect to it with a raw client
- Use a tool (netstat, lsof, ss) to list which ports are open and which programs own them on your machine
Examples
- A web server binds to port 443 (HTTPS) and port 80 (HTTP) simultaneously, using two separate sockets
- localhost:3000 and localhost:5432 can run a web app and a database on the same machine without conflict because they use different ports
Resources
Mastery checklist
- I can explain the difference between an IP address and a port number
- I can explain why a socket is described as a kind of file descriptor
- I can list which ports are open on a machine using a command-line tool
- I can explain why two services can't bind to the same port on the same machine simultaneously