Sub topic 4
IP addresses and ports: how machines are addressed
This chapter assumes you can read a URL, know that a browser talks to servers over a network, and have a rough idea of what an IP address is. The previous chapters covered how the browser parses a URL and checks its local state. Here we look at what the browser needs before it can send a single byte: the address of a machine and the number of a service on that machine.
Two questions: which machine, which program
A host name like example.com is for people. Networks forward packets using numbers. Delivering data takes two pieces of addressing:
- An IP address identifies a network interface on a machine, such as
203.0.113.10. Routers use it to move packets across the internet to the right machine. - A port is a 16-bit number (0 to 65535) that identifies a program on that machine. The operating system uses it to hand incoming data to the right process.
The IP address is the building's street address. The port is the apartment number.
In the URL https://example.com:8443/docs, the host part resolves to an IP address through DNS (the next chapter). The port 8443 comes straight from the URL. When the URL has no port, the browser uses the default for the scheme.
IPv4 addresses
An IPv4 address is a 32-bit number, written as four decimal bytes separated by dots: 203.0.113.10. Each byte ranges from 0 to 255. That allows about 4.3 billion addresses, which is fewer than the number of internet-connected devices.
An address has two logical parts, a network prefix and a host part. A notation called CIDR shows where the split is. 192.168.1.0/24 means the first 24 bits are the network and the last 8 bits identify hosts within it. Your machine uses this to decide whether a destination is on the same local network, in which case it sends directly. Otherwise it sends the packet to its default gateway, usually your router.
Special ranges you will meet
| Range | Meaning |
|---|---|
| `127.0.0.0/8` | Loopback. Traffic never leaves your machine. `localhost` normally maps to `127.0.0.1`. |
| `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` | Private ranges. Not routable on the public internet. |
| `169.254.0.0/16` | Link-local. Assigned automatically when no DHCP server answers. |
| `0.0.0.0` | "Any address" when a server binds a socket. It is not a valid destination. |
| `203.0.113.0/24`, `198.51.100.0/24`, `192.0.2.0/24` | Reserved for documentation and examples. |
IPv6 addresses
An IPv6 address is 128 bits, written as eight groups of four hexadecimal digits separated by colons. Leading zeros in a group can be dropped, and one run of all-zero groups can be replaced by ::. So 2001:0db8:0000:0000:0000:0000:0000:0001 is written 2001:db8::1. The loopback address is ::1.
IPv6 has enough addresses that every device can have a globally unique one. Most networks today run both protocols, which is called dual stack. DNS can return IPv4 records (A) and IPv6 records (AAAA) for the same name. Browsers often try IPv6 first and fall back to IPv4 quickly if it does not connect, a strategy known as Happy Eyeballs.
An IPv6 address contains colons, so a URL must wrap it in square brackets to separate it from the port:
http://[2001:db8::1]:8080/statusInspecting addresses in code
Python's standard ipaddress module parses both versions and classifies them:
import ipaddress
for text in ["93.184.216.34", "192.168.1.20", "127.0.0.1", "2001:db8::1", "::1"]:
ip = ipaddress.ip_address(text)
print(f"{text:<15} IPv{ip.version} global={ip.is_global} loopback={ip.is_loopback}")It prints:
93.184.216.34 IPv4 global=True loopback=False
192.168.1.20 IPv4 global=False loopback=False
127.0.0.1 IPv4 global=False loopback=True
2001:db8::1 IPv6 global=False loopback=False
::1 IPv6 global=False loopback=Trueis_global is false for private, loopback, link-local and documentation addresses. Use it rather than is_private when you need "reachable from the public internet".
Ports and default ports
Port numbers fall into three conventional ranges:
- 0 to 1023, well-known ports. Assigned to standard services. On Unix-like systems, binding one usually requires elevated privileges.
- 1024 to 49151, registered ports. Used by many applications, such as
5432for PostgreSQL. - 49152 to 65535, dynamic or ephemeral ports. Picked by the operating system for outgoing connections. Linux uses 32768 to 60999 by default, so the exact range varies by system.
The browser does not ask you for a port because each scheme has a default:
| Scheme | Default port |
|---|---|
| `http` | 80 |
| `https` | 443 |
| `ws` | 80 |
| `wss` | 443 |
| `ftp` | 21 |
Because of this, the standard URL class hides the port when it matches the scheme's default:
const a = new URL('https://example.com/');
const b = new URL('https://example.com:443/');
const c = new URL('https://example.com:8443/');
console.log(a.port); // ''
console.log(b.port); // '' (443 is the default for https, so it is dropped)
console.log(c.port); // '8443'
console.log(c.host); // 'example.com:8443' (host includes the port, hostname does not)The browser treats https://example.com and https://example.com:8443 as different origins. Cookies and the same-origin policy care about the port as well as the host.
Both ends of a connection have a port
The server listens on a well-known port, such as 443. The client also needs a port so that replies can find the right process. The operating system picks a random ephemeral port for each new outgoing connection.
A TCP connection is identified by four values:
- Client IP address
- Client port
- Server IP address
- Server port
This is the 4-tuple. It explains why a server listening on one port can handle thousands of simultaneous clients. Each connection has a different client address or client port, so the tuples differ even though the server side is the same. Browsers also open several parallel connections to the same server, each using a different ephemeral port.
You can see both ends from a script:
import socket
with socket.create_connection(("example.com", 80), timeout=5) as s:
print("local: ", s.getsockname()) # your IP and ephemeral port
print("remote:", s.getpeername()) # the server IP and port 80Run it twice. The remote side stays the same, but the local port changes each time.
Private addresses and NAT
Your laptop usually has a private address such as 192.168.1.20. The public internet cannot route to it. Your router performs Network Address Translation (NAT). When a packet leaves, the router rewrites the source address to its own public address and the source port to one it chooses. It records the mapping in a table. When the reply arrives, it looks up the mapping and rewrites the destination back.
NAT has consequences you will run into:
- Outgoing connections work with no setup. Incoming connections to a device behind NAT fail unless you configure port forwarding.
- The server sees the router's public address, not your laptop's. Many people on one network can share a single public IP.
- Idle mappings expire. Long-lived connections need periodic traffic (keepalives) or the router may silently drop them.
Common errors and what they mean
- Connection refused. The machine was reached, but no program is listening on that port. The operating system answers with a reset. Check that the port number is right and the service is running.
- Connection timed out. No answer came back. A firewall may be dropping packets, the address may be unroutable, or the host may be down.
- Server works on
localhostbut not from another machine. The server probably bound to127.0.0.1, which only accepts local connections. Binding to0.0.0.0(all IPv4 interfaces) or::(all IPv6 interfaces) accepts outside traffic, subject to firewall rules. localhostbehaves differently from127.0.0.1.localhostcan resolve to::1first. If your server listens only on IPv4, the IPv6 attempt fails before the fallback.- Address already in use. Another process, or a connection lingering in a closing state, holds that port.
Seeing addresses on your own machine
On Linux, ss lists connections with both endpoints:
ss -tn state establishedEach line shows a local address and port, then a peer address and port. While a browser has pages open, you will see many entries whose peer port is 443, each with a different local ephemeral port. On macOS, netstat -an -p tcp shows similar data.
What comes next
At this point the browser has a host name and a port, but it still needs an IP address for that name. The next chapter covers DNS resolution. After that, the browser can open a TCP connection to the resulting IP address and port.
Exercise
Your laptop at 192.168.1.20 opens two tabs to https://example.com. The server's IP is 203.0.113.10. What do the two connections have in common, and what must differ for the server to tell them apart? Would the URL https://example.com:443/ change anything?
Show answer
Both connections go to the same server IP (203.0.113.10) and the same server port (443, the default for https), and both start from the same client IP (192.168.1.20). They must differ in the client's ephemeral port, because the 4-tuple of client IP, client port, server IP and server port has to be unique for each connection. Writing https://example.com:443/ changes nothing. The URL parser drops the port when it matches the scheme's default, and the browser connects to port 443 either way.