Networking Tutorial · Networking Basics · Lesson 7 of 28
Ports and Sockets
How one machine runs many network services at once: ports, sockets, and the 5-tuple that identifies a connection.
Ports
An IP address gets packets to a host; a port (0 to 65535) gets them to the right program on that host. A web server listens on port 443, a database on 5432, SSH on 22.
| Port | Service |
|---|---|
| 22 | SSH |
| 53 | DNS |
| 80 / 443 | HTTP / HTTPS |
| 3306 / 5432 | MySQL / PostgreSQL |
| 6379 | Redis |
| 8080, 3000, 8000 | common development servers |
Ports below 1024 are well-known ports. When your program connects out, the operating system picks a temporary ephemeral port for your side (on Linux, 32768 to 60999 by default).
Sockets and the 5-tuple
A socket is one end of a connection. A TCP connection is identified by its 5-tuple: protocol, source IP, source port, destination IP and destination port. That is how a server on port 443 keeps thousands of clients apart: each has a different source IP and port.
import random
random.seed(7)
server = ("10.0.1.10", 443)
connections = set()
for client_ip in ["203.0.113.5", "203.0.113.5", "198.51.100.20"]:
client_port = random.randint(32768, 60999) # ephemeral port chosen by the client OS
connections.add(("tcp", client_ip, client_port, *server))
for conn in sorted(connections):
print(conn)
print(len(connections), "distinct connections to the same server port")
Output
('tcp', '198.51.100.20', 45705, '10.0.1.10', 443)
('tcp', '203.0.113.5', 37711, '10.0.1.10', 443)
('tcp', '203.0.113.5', 43379, '10.0.1.10', 443)
3 distinct connections to the same server portSeeing ports on your machine
$ ss -tlnp # Linux: listening TCP sockets
State Local Address:Port Process
LISTEN 0.0.0.0:22 sshd
LISTEN 127.0.0.1:5432 postgres
$ lsof -iTCP -sTCP:LISTEN # macOS
A server listening on 127.0.0.1 accepts only local connections; on 0.0.0.0 it accepts connections on every
interface. "Works locally, refused in Docker or the cloud" is often a server bound to 127.0.0.1.
Test yourself
A service works with curl on the server itself but is refused from other machines. What's a likely cause?
It listens on 127.0.0.1 instead of 0.0.0.0The client's ephemeral port is too highPort 443 is reserved for DNSTCP only allows one client per port
Show answer
Answer: It listens on 127.0.0.1 instead of 0.0.0.0
Binding to the loopback address accepts only local connections. Bind to 0.0.0.0 (or the interface's address), then check firewalls.