IP Addressing: IPv4/IPv6, Private Ranges, CIDR & Subnet Math, Gateways, Routing Tables, ARP/NDP
"Forwarding in the Internet is done on a longest-match basis." — Fuller & Li, RFC 4632: Classless Inter-domain Routing (CIDR), August 2006, §5.1
Summary: An IP address is a number with a split in it: the left part names a network, the right part names a host on it, and every routing, firewall, VPC and Kubernetes decision is arithmetic on that split. Focus: IPv4 and IPv6 anatomy, CIDR and subnet math you can do in your head, the special ranges, ARP/NDP, routing tables and the default gateway, binding addresses, and address planning for VPCs, Docker and Kubernetes. Learning goal: Compute any subnet by hand, read a routing table and a neighbor cache, plan non-overlapping ranges for a cloud + container platform, and handle client IPs correctly in Go and Laravel.
This page is the complete reference for IP addressing as a developer meets it: on a laptop, in a Docker network, in an AWS VPC and in a Kubernetes cluster. It covers IPv4 anatomy, the historical classes and CIDR, subnet masks and prefix lengths with worked math for /24, /27, /30, /31 and /32, VLSM, every special range you will see in logs (RFC 1918, loopback, link-local, CGNAT, multicast, documentation, 0.0.0.0, 255.255.255.255), IPv6 (notation, :: compression, /64, /56, /48, ULA, link-local, SLAAC vs DHCPv6, dual stack, zone IDs, [::1]:8080), ARP and NDP, routing tables with longest-prefix match, binding addresses, and storing IPs in PostgreSQL and Laravel. It deliberately links rather than re-teaches its neighbours: the layer model and encapsulation are in Network Models; NAT, DHCP and CGNAT mechanics in NAT, DHCP & Port Forwarding; sockets, ports and ss in Ports, Sockets & Connections; the Docker and Kubernetes network models in Docker Networking and Kubernetes Networking; security groups and NACLs in Firewalls; tunnels in VPNs & Tunnels; name resolution in DNS Resolution; and authoritative DNS, GeoDNS and anycast in IP, DNS & GeoDNS.
Page map
| If you are looking for | Go to |
|---|---|
| Tables to memorise in one minute | Everything in one minute |
| Why addresses have a network part at all | Why it exists |
| RFC 791, classes, CIDR, RFC 1918, IPv6 history | Where it comes from |
| 32 bits, dotted quad, binary, hex | IPv4 anatomy |
| Class A/B/C and why they died | Classful addressing |
| /n, masks, wildcard masks | CIDR and prefix length |
| Network, broadcast, first, last, host count; the head trick | Subnet math |
| Splitting a /16 for VPC, Docker, pods | VLSM |
| 10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, 100.64/10, 224/4 | Special ranges |
0.0.0.0 vs 255.255.255.255 | The two extreme addresses |
128 bits, ::, /64, ULA, fe80::/10, zone IDs, [::1]:8080 | IPv6 |
| SLAAC, DHCPv6, dual stack, why NAT is rare | SLAAC, DHCPv6, dual stack |
| IP to MAC on IPv4, gratuitous ARP, spoofing | ARP |
| Neighbor Discovery on IPv6 | NDP |
| Routing table, longest-prefix match, default gateway, metric | Routing |
| The exact steps when your laptop sends a packet | How a packet leaves your laptop |
127.0.0.1 vs 0.0.0.0 vs ::, the Docker bind bug | Binding and listening |
| AWS VPC, reserved addresses, IGW, NAT gateway, GCP | Cloud VPC addressing |
| Docker pools, Compose subnets, pod/service/node CIDRs | Container and Kubernetes planning |
inet/cidr, X-Forwarded-For, GeoIP | IPs in databases and logs |
| Tools and platforms side by side | Per-tool and per-platform behaviour |
| Bitwise AND, ARP bytes, neighbor states, errno values, sysctls | Mechanics |
| Go + Laravel fixes for the classic bugs | Solving the classic problems |
| Symptom → cause → fix | Troubleshooting |
| Which prefix size for what | Choosing |
| Monolith to multi-region | In architecture |
| Hands-on | Lab |
| Wrong beliefs, a cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
Prefix sizes you meet every week. Every row is unpacked in Subnet math.
| Prefix | Mask | Addresses | Usable hosts (classic LAN) | Where you see it |
|---|---|---|---|---|
| /8 | 255.0.0.0 | 16,777,216 | 16,777,214 | 10.0.0.0/8, 127.0.0.0/8 |
| /12 | 255.240.0.0 | 1,048,576 | 1,048,574 | 172.16.0.0/12, kubeadm Service CIDR 10.96.0.0/12 |
| /16 | 255.255.0.0 | 65,536 | 65,534 | AWS VPC maximum, Docker 172.17.0.0/16 |
| /20 | 255.255.240.0 | 4,096 | 4,094 (AWS: 4,091) | Private subnet for Kubernetes nodes |
| /24 | 255.255.255.0 | 256 | 254 (AWS: 251) | Home LAN, one Kubernetes node's pod range |
| /27 | 255.255.255.224 | 32 | 30 | Small DMZ or database subnet |
| /28 | 255.255.255.240 | 16 | 14 (AWS: 11) | AWS smallest subnet |
| /30 | 255.255.255.252 | 4 | 2 | Old-style point-to-point link |
| /31 | 255.255.255.254 | 2 | 2 (RFC 3021) | Modern point-to-point link |
| /32 | 255.255.255.255 | 1 | 1 | One host: a route, an allow-list entry |
| /64 (IPv6) | n/a | 2^64 | all | Every IPv6 LAN segment |
Special ranges. Every row is unpacked in Special ranges.
| Range | Name | Plain words |
|---|---|---|
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | Private (RFC 1918) | Reuse freely inside your network; never routed on the internet |
100.64.0.0/10 | Shared Address Space / CGNAT (RFC 6598) | Your ISP's NAT; also Tailscale's range |
127.0.0.0/8, ::1 | Loopback | Never leaves the host |
169.254.0.0/16, fe80::/10 | Link-local | Valid only on one link; 169.254.169.254 is the cloud metadata service |
224.0.0.0/4, ff00::/8 | Multicast | One-to-many groups (mDNS 224.0.0.251) |
fc00::/7 (in practice fd00::/8) | Unique Local Address (ULA, RFC 4193) | IPv6's "private" range |
192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32 | Documentation (RFC 5737, RFC 3849) | Use in examples and tests, never in production |
0.0.0.0, :: | Unspecified | As a bind address: all interfaces. As a route: default |
255.255.255.255 | Limited broadcast | Everyone on this link, never forwarded |
Five commands.
| Question | Linux | macOS |
|---|---|---|
| What are my addresses? | ip -br addr | ifconfig |
| Which route will this destination use? | ip route get 1.1.1.1 | route -n get 1.1.1.1 |
| What is in my routing table? | ip route / ip -6 route | netstat -rn |
| Who are my neighbors (IP → MAC)? | ip neigh | arp -an, ndp -an |
| Is this address inside that subnet? | ipcalc, sipcalc, Go netip.Prefix.Contains | same |
Why it exists
A router cannot keep one entry per machine on Earth. So an address is split in two: a network part that routers use to forward the packet toward the right place, and a host part that only matters on the final link. Every routing table, every firewall rule and every cloud route table is a list of network parts. Subnetting is choosing where the split goes; CIDR is writing that choice as /n.
| Short prefix (big block, e.g. /16) | Long prefix (small block, e.g. /28) |
|---|---|
| Room for growth, one route covers everything | Little waste; fits tiny tiers |
| One broadcast/failure domain for many hosts | Many subnets, many route-table entries |
| Easy to collide with another network's range | Easy to run out of addresses (pods!) |
| Fewer firewall rules | Fine-grained security boundaries |
The analogy we reuse on this page: postal addresses. The network part is "city + street"; the host part is the house number. The post office in another country only reads the city (longest-prefix match: the most specific part it knows). Only the local postman reads the house number, and he knows which door is which by walking the street (ARP/NDP: asking "who lives at number 7?"). The default gateway is the post box at the corner: anything not for your own street goes there.
Three common misunderstandings, up front
- "An IP address identifies a machine." It identifies an interface on a network, and only for now: a laptop has a loopback, a Wi-Fi, a VPN and a Docker bridge address at once, and DHCP, SLAAC privacy addresses and NAT change them.
- "/24 means 255 hosts." It means 256 addresses; on a classic IPv4 LAN two are unusable (network and broadcast) so 254; AWS reserves five, so 251.
- "
127.0.0.1and0.0.0.0are both 'localhost'." As a bind address,127.0.0.1accepts only connections from the same network namespace;0.0.0.0accepts on every IPv4 interface. Inside a container that difference decides whether your app is reachable at all (Binding).
Where it comes from
- RFC 791 (September 1981) defines IPv4 with a header field
Source Address: 32 bitsandDestination Address: 32 bits. Addresses were split by class: the first bits of the address told you where the network part ended. - RFC 826 (November 1982) defines ARP, "An Ethernet Address Resolution Protocol", the glue between 32-bit IP addresses and 48-bit Ethernet addresses.
- RFC 919 (October 1984): "The address 255.255.255.255 denotes a broadcast on a local hardware network, which must not be forwarded."
- RFC 1112 (August 1989) reserves the class D range "from 224.0.0.0 to 239.255.255.255" for multicast. RFC 1122 (October 1989) requires that
{ 127, <any> }loopback addresses "MUST NOT appear outside a host". - CIDR, 1993 (RFC 1519), updated as RFC 4632 (August 2006). Classes wasted space and exploded routing tables. RFC 4632 §3.1 describes the fix: a prefix is "followed by the "/" (slash) character, followed by a decimal value between 0 and 32 that describes the number of significant bits."
- RFC 1918 (February 1996) reserves three private blocks for "private internets":
10.0.0.0 - 10.255.255.255 (10/8 prefix),172.16.0.0 - 172.31.255.255 (172.16/12 prefix),192.168.0.0 - 192.168.255.255 (192.168/16 prefix). - RFC 3021 (December 2000) allows /31 on point-to-point links, halving the space spent on router links.
- IPv6: RFC 2460 (1998), now RFC 8200 (July 2017) with "128-bit address of the originator". RFC 4291 (February 2006) is the addressing architecture (
::1loopback,fe80::/10link-local, IPv4-mapped::ffff:a.b.c.d). RFC 4193 (October 2005) reservesFC00::/7for unique local addresses. RFC 4861/4862 (September 2007) define Neighbor Discovery and Stateless Address Autoconfiguration. RFC 5952 (August 2010) fixes the canonical text form. RFC 6177 (March 2011) relaxes the old "/48 per site" advice toward /56 for end sites. - RFC 6598 (April 2012): "The Shared Address Space address range is 100.64.0.0/10", for carrier-grade NAT. RFC 6890 (April 2013) and the IANA special-purpose registries collect every special range in one table.
The concept catalogue
Each block: plain words, the usual wrong belief, a precise definition, a step sequence, real scenarios, per-platform behaviour, and the fix in Go and Laravel (full code in Solving the classic problems).
IPv4 address anatomy Must-know
In plain words: an IPv4 address is one 32-bit number. 10.0.12.7 is just a friendly way of writing four bytes: 10, 0, 12, 7.
Common misunderstanding: "The dots separate network and host." They separate bytes (octets) for human eyes only. The network/host boundary is set by the prefix length and can fall in the middle of an octet (/20 splits the third byte).
Definition: a 32-bit unsigned integer, written as four decimal octets 0–255 (dotted quad), stored big-endian ("network byte order") in packets. 10.0.12.7 = 0x0A000C07 = 167,775,239.
Converting 10.0.12.7 by hand
1 split at dots 10 0 12 7
2 each octet to binary 00001010 00000000 00001100 00000111
3 each octet to hex 0a 00 0c 07
4 as one integer 10*2^24 + 0*2^16 + 12*2^8 + 7 = 167775239The same four bytes on the wire (from printf '\x0a\x00\x0c\x07' | xxd on the author's machine) and as sipcalc sees them:
00000000: 0a00 0c07 ....
Host address (decimal) - 167775239
Host address (hex) - A000C07Real scenario: a log line shows 167775239 in an old MySQL column created with INET_ATON(); an allow-list check written with string prefixes (startsWith("10.0.1")) matches 10.0.13.5 by accident; a parser accepts 010.1.2.3 and some libraries read the leading zero as octal (PHP's FILTER_VALIDATE_IP rejects it, see the lab).
| Notation | Example | Who accepts it |
|---|---|---|
| Dotted quad | 10.0.12.7 | Everyone |
| Integer | 167775239 | ping 167775239 (inet_aton), MySQL INET_NTOA() |
| Hex | 0x0A000C07 | inet_aton; Go netip.ParseAddr rejects |
| Leading zeros | 010.0.12.7 | Ambiguous (octal in inet_aton); Go and PHP filter reject |
| IPv4-mapped IPv6 | ::ffff:10.0.12.7 | Dual-stack sockets report IPv4 peers like this |
Fix / how to use it: parse with a strict parser (netip.ParseAddr in Go, filter_var(..., FILTER_VALIDATE_IP) or Laravel's ip rule in PHP) and compare as numbers or prefixes, never as strings.
Classful addressing (historical) Good to know
In plain words: before 1993 the first bits of an address fixed the network size: Class A (/8), B (/16), C (/24).
Common misunderstanding: "10.x is a Class A, so its mask is 255.0.0.0." Classes have not existed in routing since CIDR. 10.20.30.0/24 is a perfectly normal network; the mask is whatever the prefix says.
Definition:
| Class | Leading bits | First octet | Implied mask | Today |
|---|---|---|---|---|
| A | 0 | 0–127 | /8 | Legacy name only |
| B | 10 | 128–191 | /16 | Legacy name only |
| C | 110 | 192–223 | /24 | Legacy name only |
| D | 1110 | 224–239 | n/a | Multicast 224.0.0.0/4 |
| E | 1111 | 240–255 | n/a | Reserved 240.0.0.0/4 |
RFC 1918 still describes its blocks in classful terms: "the first block is nothing but a single class A network number, while the second block is a set of 16 contiguous class B network numbers, and third block is a set of 256 contiguous class C network numbers."
Real scenario: an old Windows dialog pre-fills 255.0.0.0 when you type 10.1.1.5; an interview asks "what class is 172.20.0.1"; legacy firewall configs talk about "class C" when they mean /24.
Fix: always write the prefix length explicitly.
CIDR, prefix length and subnet mask Must-know
In plain words: /20 means "the first 20 bits are the network". The subnet mask is the same fact written as 32 bits: twenty 1s then twelve 0s.
Common misunderstanding: "10.0.12.7/20 is a network." It is a host address with its prefix length. The network is 10.0.0.0/20. PostgreSQL makes the distinction a type: inet accepts 10.0.12.7/20, cidr rejects it with Value has bits set to right of mask.
Definition: a CIDR block A/n is the set of addresses whose first n bits equal the first n bits of A. Mask = n ones followed by 32-n zeros. Wildcard mask (Cisco ACLs, sipcalc's "Cisco wildcard") = the inverted mask, 0.0.15.255 for /20. Address AND mask = network address. Address OR wildcard = broadcast.
Address AND mask, bit by bit (10.0.12.7/20)
1 address 00001010.00000000.0000 1100.00000111
2 mask 11111111.11111111.1111 0000.00000000 = 255.255.240.0
3 AND 00001010.00000000.0000 0000.00000000 = 10.0.0.0 (network)
4 OR wild 00001010.00000000.0000 1111.11111111 = 10.0.15.255 (broadcast)| Mask octet value | Prefix bits in that octet | Block size in that octet |
|---|---|---|
| 255 | 8 | 1 |
| 254 | 7 | 2 |
| 252 | 6 | 4 |
| 248 | 5 | 8 |
| 240 | 4 | 16 |
| 224 | 3 | 32 |
| 192 | 2 | 64 |
| 128 | 1 | 128 |
| 0 | 0 | 256 |
Real scenario: an AWS security group rule 10.0.0.0/16 that you meant to be one subnet; a Kubernetes --cluster-cidr copied from a blog that collides with the VPC; a nginx set_real_ip_from 10.0.0.0/8 that also trusts every pod.
Fix: let a library mask it: Go netip.MustParsePrefix("10.0.12.7/20").Masked() → 10.0.0.0/20; PostgreSQL network('10.0.12.7/20'::inet); PHP SubnetMath::describe() below.
Subnet math: network, broadcast, first, last, host count Must-know
In plain words: find the block size, find which block the address falls in, then the first address of the block is the network, the last is the broadcast, and everything between is hosts.
Common misunderstanding: "The last usable address of 192.168.1.64/27 is .95." .95 is the broadcast; the last host is .94. Off-by-one at the broadcast is the classic subnet bug.
Definition: for IPv4 A/n with h = 32 - n host bits: total = 2^h; network = A with host bits 0; broadcast = A with host bits 1; usable = 2^h − 2, except /31 (RFC 3021: both addresses usable on a point-to-point link) and /32 (a single host). IPv6 has no broadcast, so every address in the block is assignable (the all-zero interface ID is the Subnet-Router anycast address).
The head trick (any prefix, no binary):
192.168.1.77/27 in your head
1 which octet holds the boundary? /27 -> 4th octet (24 < 27 <= 32)
2 bits of prefix in that octet 27 - 24 = 3 -> mask octet 224
3 block size 256 - 224 = 32
4 multiples of 32 0, 32, 64, 96 ... 77 falls in 64..95
5 network / broadcast 192.168.1.64 / 192.168.1.95
6 hosts .65 .. .94 (32 - 2 = 30)Worked results, produced by the Go tool in this chapter (go run ./subnetcalc <prefix>):
| Input | Network | Broadcast | First host | Last host | Total | Usable |
|---|---|---|---|---|---|---|
192.168.1.0/24 | 192.168.1.0 | 192.168.1.255 | .1 | .254 | 256 | 254 |
192.168.1.64/27 | 192.168.1.64 | 192.168.1.95 | .65 | .94 | 32 | 30 |
10.0.0.4/30 | 10.0.0.4 | 10.0.0.7 | .5 | .6 | 4 | 2 |
10.0.0.0/31 | 10.0.0.0 | none (RFC 3021) | .0 | .1 | 2 | 2 |
10.0.0.9/32 | 10.0.0.9 | none (host) | .9 | .9 | 1 | 1 |
10.0.12.7/20 | 10.0.0.0 | 10.0.15.255 | 10.0.0.1 | 10.0.15.254 | 4096 | 4094 |
Real output for the last row:
$ go run ./subnetcalc 10.0.12.7/20
input 10.0.12.7/20
network 10.0.0.0/20
netmask 255.255.240.0
broadcast 10.0.15.255
binary 00001010.00000000.0000|1100.00000111
hosts 10.0.0.1 .. 10.0.15.254
total 4096
usable 4094And ipcalc (Alpine ipcalc package) agrees:
$ ipcalc 10.0.12.7/20
Address: 10.0.12.7
Network: 10.0.0.0/20
Netmask: 255.255.240.0 = 20
Broadcast: 10.0.15.255
Address space: Private Use
HostMin: 10.0.0.1
HostMax: 10.0.15.254
Hosts/Net: 4094Real scenario: sizing a database subnet that must hold 3 primaries, 6 replicas, a proxy pair and future growth (/27 is 30 hosts, AWS gives 27); router-to-router links numbered with /31 to save space; a firewall allow-list of one office IP as /32.
Fix: never compute by string slicing; use the calculator (Go, PHP).
VLSM: splitting a block into subnets of different sizes Important
In plain words: Variable Length Subnet Masking means carving one big block into children of different sizes, biggest first, each on its own boundary.
Common misunderstanding: "I can start a /20 anywhere." A /20 must start on a multiple of 4,096 addresses (third octet a multiple of 16). 10.0.8.0/20 is invalid as a network; it masks to 10.0.0.0/20 and silently overlaps the neighbour.
Definition: a block /n splits into 2^(m−n) children of /m. Allocate largest first, align each child to its own size, record every allocation, and leave gaps for growth.
Splitting 10.0.0.0/16 for one VPC + one Kubernetes cluster
1 /16 -> two /17: 10.0.0.0/17 (VPC subnets) 10.0.128.0/17 (pod CIDR)
2 10.0.0.0/17 -> public /24s: 10.0.0.0/24, 10.0.1.0/24, 10.0.2.0/24
3 10.0.0.0/17 -> private /20s: 10.0.16.0/20, 10.0.32.0/20, 10.0.48.0/20
4 databases /20: 10.0.64.0/20 (spare: 10.0.80.0/20 ...)
5 10.0.128.0/17 -> /24 per node: 10.0.128.0/24 ... 10.0.255.0/24 = 128 nodes
6 Service CIDR outside the VPC: 172.20.0.0/16go run ./subnetcalc -split 18 10.0.0.0/16 prints 10.0.0.0/18 10.0.64.0/18 10.0.128.0/18 10.0.192.0/18; -split 24 prints 256 /24s.
Real scenario: one VPC per environment with identical layouts (10.10/16 dev, 10.20/16 staging, 10.30/16 prod) so peering never collides; a /24 per Docker host for a Swarm overlay; per-team /20s in a shared VPC.
Fix: keep the plan in code (a Terraform map or a YAML file) and check it with an overlap test (Overlapping CIDRs).
Special and private ranges Must-know
In plain words: some address blocks have reserved meanings. Seeing one in a log tells you where the packet came from.
Common misunderstanding: "172.x is private." Only 172.16.0.0 to 172.31.255.255 is. 172.32.0.1 and 172.15.0.1 are public internet addresses. Equally, 100.64.x.x looks public but is CGNAT.
Definition (IANA special-purpose registries, RFC 6890):
| Block | RFC | Meaning | Routed on the internet? | Typical sighting |
|---|---|---|---|---|
0.0.0.0/8 | 791/6890 | "This network"; 0.0.0.0 = unspecified | No | Bind address, default route |
10.0.0.0/8 | 1918 | Private | No | VPCs, corporate LANs |
100.64.0.0/10 | 6598 | Shared Address Space (CGNAT) | No | Mobile ISPs, Tailscale, EKS custom networking |
127.0.0.0/8 | 1122 | Loopback | No (must not leave the host) | localhost |
169.254.0.0/16 | 3927 | IPv4 link-local | No | DHCP failed; 169.254.169.254 cloud metadata |
172.16.0.0/12 | 1918 | Private | No | Docker 172.17.0.0/16 and friends |
192.0.2.0/24 | 5737 | TEST-NET-1 documentation | No | Docs and tests |
192.168.0.0/16 | 1918 | Private | No | Home routers, Docker pool 192.168.0.0/16 |
198.18.0.0/15 | 2544 | Benchmarking | No | Network test labs |
198.51.100.0/24 | 5737 | TEST-NET-2 documentation | No | Docs and tests |
203.0.113.0/24 | 5737 | TEST-NET-3 documentation | No | Docs and tests |
224.0.0.0/4 | 1112 | Multicast | Scoped | mDNS 224.0.0.251, VRRP 224.0.0.18 |
240.0.0.0/4 | 1112 | Reserved (former class E) | No | Never assign |
255.255.255.255/32 | 919 | Limited broadcast | No | DHCP discover |
::1/128 | 4291 | IPv6 loopback | No | localhost on IPv6 |
::/128 | 4291 | IPv6 unspecified | No | Bind [::] |
::ffff:0:0/96 | 4291 | IPv4-mapped | No | Dual-stack socket peers |
fc00::/7 | 4193 | Unique Local Address | No | Docker IPv6 pools, private IPv6 |
fe80::/10 | 4291 | IPv6 link-local | No | Every IPv6 interface, NDP |
ff00::/8 | 4291 | IPv6 multicast | Scoped | ff02::1 all nodes |
2001:db8::/32 | 3849 | IPv6 documentation | No | Docs and tests |
Real output of the Go classifier in this chapter:
$ go run ./clientip
10.2.3.4 rfc1918
100.72.1.9 cgnat
169.254.169.254 link-local
fd12:3456::1 ula
fe80::1 link-local
::ffff:192.168.1.10 rfc1918
8.8.8.8 public
198.51.100.7 documentation
224.0.0.251 multicast
:: unspecifiedReal scenario: SSRF: a webhook URL that resolves to 169.254.169.254 leaks cloud credentials (block link-local, loopback, RFC 1918, CGNAT and ULA); analytics that geolocate 10.x addresses because the app logged the load balancer, not the client; a test suite that uses 8.8.8.8 instead of 192.0.2.1 and makes real calls.
Fix: Go netip.Addr.IsPrivate(), IsLoopback(), IsLinkLocalUnicast() (note: IsPrivate covers RFC 1918 and fc00::/7 but not CGNAT, so the classifier adds 100.64.0.0/10); PHP filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE) (PHP 8.2+).
The two extreme addresses: 0.0.0.0 and 255.255.255.255 Important
In plain words: 0.0.0.0 means "no specific address": as a listen address, "every address I have"; as a route, "everything" (the default route 0.0.0.0/0). 255.255.255.255 means "everyone on this wire".
Common misunderstanding: "I can connect to 0.0.0.0." On Linux and macOS, connecting to 0.0.0.0 happens to reach the local host, but it is undefined as a destination; browsers are blocking it. Never put 0.0.0.0 in a client URL.
Definition: 0.0.0.0 is the IPv4 unspecified address (:: in IPv6). In a bind call it selects INADDR_ANY. In a routing table, 0.0.0.0/0 (default) matches every destination with the shortest possible prefix, so it only wins when nothing more specific matches. 255.255.255.255 is the limited broadcast, "which must not be forwarded" (RFC 919). The directed broadcast of a subnet (10.0.15.255 for 10.0.0.0/20) is a different thing and is usually dropped by routers.
0.0.0.0 in three roles
1 bind listen(0.0.0.0:8080) -> accept on every IPv4 interface
2 route 0.0.0.0/0 via 10.0.0.1 -> default route, prefix length 0
3 source DHCP DISCOVER 0.0.0.0 -> 255.255.255.255 (no address yet)Real scenario: a Docker image whose app listens on 127.0.0.1 works in docker exec and fails from the host (Binding); a Terraform security group with 0.0.0.0/0 opens a database to the world; a DHCP client that cannot reach a server ends up with 169.254.x.x.
Fix: bind servers to 0.0.0.0 (or [::]) inside containers and to a specific private IP on multi-homed hosts; never accept 0.0.0.0/0 in a firewall rule without review.
IPv6 addressing Must-know
In plain words: IPv6 addresses are 128 bits written as eight groups of four hex digits. The first half (/64) names the network, the second half names the interface. There are so many that every LAN gets 2^64 addresses.
Common misunderstanding: "fe80::1 is enough to reach a neighbor." Link-local addresses exist on every interface, so you must say which one: fe80::1%en0 (the zone ID). And in a URL the address must be in brackets: http://[::1]:8080/, otherwise the colons look like a port.
Definition: 128 bits, eight 16-bit groups, lowercase hex; leading zeros in a group may be dropped; one run of all-zero groups may be replaced by ::. RFC 5952 makes it canonical: "The use of the symbol "::" MUST be used to its maximum capability. For example, 2001:db8:0:0:0:0:2:1 must be shortened to 2001:db8::2:1." Hex digits are written lowercase.
Shortening 2001:0db8:abcd:0012:0000:0000:0000:0001
1 drop leading zeros per group 2001:db8:abcd:12:0:0:0:1
2 longest zero run -> :: 2001:db8:abcd:12::1
3 bytes on the wire 20 01 0d b8 ab cd 00 12 00 00 00 00 00 00 00 01
4 network /64 2001:db8:abcd:12::/64
5 interface ID (low 64 bits) ::100000000: 2001 0db8 abcd 0012 0000 0000 0000 0001 ...............
00000000: 0000 0000 0000 0000 0000 ffff c0a8 010a ................ <- ::ffff:192.168.1.10| Prefix | Meaning | Who gets it |
|---|---|---|
| /128 | One address | Loopback, a host route |
| /64 | One LAN segment (SLAAC requires it) | Every subnet, every Kubernetes node (--node-cidr-mask-size-ipv6 default 64) |
| /56 | 256 /64s | Typical home or small site (RFC 6177) |
| /48 | 65,536 /64s | Enterprise site |
| /32 | ISP-sized | 2001:db8::/32 documentation |
| Scope | Prefix | Example | Leaves the link? |
|---|---|---|---|
| Loopback | ::1/128 | ::1 | No |
| Link-local | fe80::/10 | fe80::1496:3daa:ddc1:3c65%en0 | No |
| Unique local (ULA) | fc00::/7 | fd00:ab:cd::2 | Inside your organisation only |
| Global unicast | 2000::/3 | 2001:db8:abcd:12::1 | Yes |
| Multicast | ff00::/8 | ff02::1, ff02::1:ff00:3 | By scope |
Real addresses from a Docker container on an IPv6 network (docker network create --ipv6 --subnet fd00:ab:cd::/64 ...):
$ ip -6 addr show eth0
inet6 fd00:ab:cd::2/64 scope global nodad
inet6 fe80::dc1b:27ff:fe16:d1a/64 scope link proto kernel_ll
$ ip -6 route
fd00:ab:cd::/64 dev eth0 proto kernel metric 256 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium
default via fd00:ab:cd::1 dev eth0 metric 1024 pref mediumThe link-local address fe80::dc1b:27ff:fe16:d1a is built from the MAC de:1b:27:16:0d:1a (modified EUI-64: flip the 7th bit de→dc, insert ff:fe in the middle). macOS and modern Linux use random or "secured" interface IDs instead (RFC 7217-style stable privacy addresses and RFC 4941 privacy extensions / temporary addresses), which is why one laptop shows several global IPv6 addresses.
Real scenario: a config DB_HOST=2001:db8::5:5432 that is parsed as a 9-group address; Go net.Dial("tcp", "::1:8080") failing (use net.JoinHostPort("::1", "8080") → [::1]:8080); a rate limiter that limits per /128 and is bypassed by a client rotating through its /64.
Fix: always build host:port with net.JoinHostPort/net.SplitHostPort (Go) and brackets in URLs; store and compare canonical form (netip.Addr.String(), PostgreSQL inet output, inet_ntop(inet_pton($ip)) in PHP); key rate limits per /64.
SLAAC, DHCPv6, dual stack and why NAT is rare in IPv6 Important
In plain words: on IPv6, a host usually configures itself: a router announces the /64 prefix and the host makes up the rest (SLAAC). DHCPv6 is optional. Most networks run IPv4 and IPv6 side by side (dual stack).
Common misunderstanding: "IPv6 needs NAT for security like IPv4." NAT in IPv4 is an address-shortage workaround; the security comes from the stateful firewall that usually sits next to it. IPv6 has enough addresses for every device, so the firewall stays and NAT (NAT66/NPTv6) is rare. See NAT, DHCP & Port Forwarding for NAT itself.
Definition:
| Mechanism | RFC | What it gives | Who decides the address |
|---|---|---|---|
| SLAAC | 4862 | Prefix from Router Advertisement + self-made interface ID | The host |
| Stateless DHCPv6 | 8415 | DNS servers etc., address still from SLAAC | Host (address), server (options) |
| Stateful DHCPv6 | 8415 | Leased addresses, like DHCPv4 | The server |
| DHCPv6 Prefix Delegation | 8415 | A whole /56 or /48 to a router | ISP's server |
| Dual stack | - | Both an IPv4 and an IPv6 address per interface | Both mechanisms |
SLAAC on a new laptop
1 host forms fe80::<id>, runs Duplicate Address Detection (NS for itself)
2 host sends Router Solicitation to ff02::2 (all routers)
3 router replies Router Advertisement: prefix 2001:db8:abcd:12::/64, M/O flags
4 host forms 2001:db8:abcd:12::<id> (+ temporary addresses), runs DAD
5 default route: via the router's fe80:: link-local addressReal scenario: Android does not implement stateful DHCPv6, so an IPv6-only office that relies on it leaves phones without addresses; a Kubernetes dual-stack cluster gives each pod one IPv4 and one IPv6 address; a client prefers IPv6 (Happy Eyeballs) and hits a server whose firewall only allows IPv4.
Fix: test both families; in Go a "tcp" listener on [::] serves both (see Binding); in Laravel make sure TrustProxies lists the IPv6 ranges of your load balancers too.
ARP: from IPv4 address to MAC address Must-know
In plain words: Ethernet and Wi-Fi deliver frames to MAC addresses, not IPs. To send to 10.250.0.3 on the same link, the host shouts "who has 10.250.0.3?" to everyone and the owner answers with its MAC.
Common misunderstanding: "ARP finds the MAC of the remote server." Only of a host on your own link. For anything off-link, ARP resolves the gateway's MAC; the IP destination stays the remote server.
Definition (RFC 826): an ARP request is a broadcast frame (destination ff:ff:ff:ff:ff:ff, EtherType 0x0806) carrying sender MAC/IP and target IP; the owner unicasts a reply. Results go into the ARP cache (neighbor table), which ages out. Gratuitous ARP is an unsolicited announcement of your own IP→MAC mapping (used after failover of a virtual IP, by keepalived/VRRP, and by RFC 5227 address-conflict detection). ARP spoofing (ARP poisoning) is answering for someone else's IP, which ARP cannot prevent because it has no authentication.
Real capture between two containers on a user-defined Docker network 10.250.0.0/24 (tcpdump -nn -e -XX arp; the request appears twice because the bridge capture sees it on the way out and back):
36:56:d7:eb:95:86 > ff:ff:ff:ff:ff:ff, ethertype ARP (0x0806), length 42: Request who-has 10.250.0.3 tell 10.250.0.4, length 28
0x0000: ffff ffff ffff 3656 d7eb 9586 0806 0001 ......6V........
0x0010: 0800 0604 0001 3656 d7eb 9586 0afa 0004 ......6V........
0x0020: 0000 0000 0000 0afa 0003 ..........
3e:9a:02:78:01:14 > 36:56:d7:eb:95:86, ethertype ARP (0x0806), length 42: Reply 10.250.0.3 is-at 3e:9a:02:78:01:14, length 28
0x0000: 3656 d7eb 9586 3e9a 0278 0114 0806 0001 6V....>..x......
0x0010: 0800 0604 0002 3e9a 0278 0114 0afa 0003 ......>..x......
0x0020: 3656 d7eb 9586 0afa 0004 6V........The bytes are decoded field by field in Mechanics. After the exchange the cache holds:
$ ip -s neigh show
10.250.0.3 dev eth0 lladdr 3e:9a:02:78:01:14 ref 1 used 1/1/1probes 4 REACHABLE
10.250.0.1 dev eth0 lladdr 5a:a3:2d:04:ca:2f ref 1 used 9/2/9probes 4 REACHABLE| Platform | See the cache | Clear it |
|---|---|---|
| Linux | ip neigh, cat /proc/net/arp | ip neigh flush dev eth0 |
| macOS | arp -an | sudo arp -d -a |
| Windows | arp -a | arp -d * |
| AWS VPC | Not visible: the VPC answers ARP itself | n/a; spoofing does not work |
| Kubernetes (Calico) | ip neigh shows 169.254.1.1 as every pod's gateway (proxy ARP) | n/a |
Real scenario: after a VRRP/keepalived failover the virtual IP moves and clients keep talking to the dead box until a gratuitous ARP updates their caches; two VMs get the same static IP and connections flap (duplicate address); a guest Wi-Fi attacker poisons the gateway entry to sniff traffic (use TLS everywhere).
Fix: you do not write ARP code; you diagnose with ip neigh (states REACHABLE, STALE, DELAY, PROBE, FAILED, INCOMPLETE) and rely on TLS, not the LAN, for confidentiality.
NDP: IPv6 Neighbor Discovery Important
In plain words: IPv6 has no ARP and no broadcast. Neighbor Discovery does the same job (and more) with ICMPv6 messages sent to a tiny multicast group derived from the target address.
Common misunderstanding: "Blocking ICMPv6 is a safe hardening step." Without ICMPv6, NDP breaks and IPv6 stops working on the link (and Path MTU discovery breaks across links).
Definition (RFC 4861): "Nodes (hosts and routers) use Neighbor Discovery to determine the link-layer addresses for neighbors known to reside on attached links and to quickly purge cached values that become invalid." Five ICMPv6 messages: Router Solicitation (133), Router Advertisement (134), Neighbor Solicitation (135), Neighbor Advertisement (136), Redirect (137). A solicitation goes to the solicited-node multicast address ff02::1:ffXX:XXXX (last 24 bits of the target), whose Ethernet MAC is 33:33:ff:XX:XX:XX. NDP also does Duplicate Address Detection and Neighbor Unreachability Detection.
Real capture (tcpdump -nn -e 'icmp6 and (ip6[40]==135 or ip6[40]==136)') between fd00:ab:cd::2 and fd00:ab:cd::3:
de:1b:27:16:0d:1a > 33:33:ff:00:00:03, ethertype IPv6 (0x86dd), length 86: fd00:ab:cd::2 > ff02::1:ff00:3: ICMP6, neighbor solicitation, who has fd00:ab:cd::3, length 32
de:6b:0c:c7:05:83 > de:1b:27:16:0d:1a, ethertype IPv6 (0x86dd), length 86: fd00:ab:cd::3 > fd00:ab:cd::2: ICMP6, neighbor advertisement, tgt is fd00:ab:cd::3, length 32
$ ip -6 neigh show dev eth0
fd00:ab:cd::3 lladdr de:6b:0c:c7:05:83 REACHABLE| Job | IPv4 | IPv6 |
|---|---|---|
| IP → MAC | ARP request/reply (broadcast) | NS/NA (solicited-node multicast) |
| Find the router | DHCP option 3 | Router Advertisement |
| Duplicate detection | RFC 5227 ARP probe | DAD (NS for own address) |
| Announce a move | Gratuitous ARP | Unsolicited NA |
| Spoofing defense | Dynamic ARP Inspection (switch) | RA Guard, SEND (rarely deployed) |
| Tool | ip neigh, arp -an | ip -6 neigh, ndp -an (macOS) |
Real scenario: a security group or host firewall that drops ICMPv6 and makes IPv6 flaky; a rogue Router Advertisement from a misconfigured laptop hijacks the default route of a whole office (RA Guard on switches stops it).
Fix: allow ICMPv6 types 133–137 on the link; diagnose with ip -6 neigh and ndp -an.
Routing table, longest-prefix match and the default gateway Must-know
In plain words: before sending, the kernel looks up the destination in its routing table. The row with the longest matching prefix wins. That row says either "it is on this link" (send directly) or "send via this gateway".
Common misunderstanding: "The first matching route wins" or "the default route is used unless..." Order does not matter; specificity does. A VPN that pushes 10.0.0.0/8 beats your LAN's default route for any 10.x address, but your LAN's 10.84.50.0/24 beats the VPN for local hosts.
Definition: each entry has a destination prefix, a next hop (via gateway) or scope link (on-link), an output device, a source hint (src) and a metric ("routes with lower values are preferred", ip-route(8)). Lookup: collect matching entries, pick the longest prefix, break ties by metric. The default gateway is the next hop of 0.0.0.0/0 (::/0). Policy routing (ip rule) picks which table to look in by source address, mark or interface before the lookup; Kubernetes CNIs and VPN clients use it.
Real routing table inside a container on 10.250.0.0/24, and the kernel's decision for two destinations:
$ ip route
default via 10.250.0.1 dev eth0
10.250.0.0/24 dev eth0 scope link src 10.250.0.2
$ ip route get 10.250.0.3
10.250.0.3 dev eth0 src 10.250.0.4 uid 0
$ ip route get 1.1.1.1
1.1.1.1 via 10.250.0.1 dev eth0 src 10.250.0.4 uid 0On the author's macOS laptop with a VPN connected (netstat -rn -f inet, trimmed; MACs masked), the VPN installs 1, 2/7, 4/6 ... 64/2 routes. Together they cover 0.0.0.0/1 and are each longer than /0, so they beat the Wi-Fi default without deleting it, while the /24 of the LAN still wins locally:
Destination Gateway Flags Netif Expire
default link#20 UCSg utun4
default 192.168.1.1 UGScIg en0
2/7 link#20 UCS utun4
64/2 link#20 UCS utun4
10 192.168.1.1 UGSc en0
192.168.1.0/24 link#12 UCS en0 !
192.168.1.1 xx:xx:xx:xx:xx:xx UHLWIir en0 1194
127 127.0.0.1 UCS lo0
$ route -n get 1.1.1.1 -> interface: utun4
$ route -n get 192.168.1.20 -> interface: en0 (on-link, no gateway)
$ route -n get 10.1.2.3 -> gateway: 192.168.1.1 interface: en0| Platform | Show table | Ask for one destination | Add a route |
|---|---|---|---|
| Linux | ip route, ip -6 route, ip rule | ip route get 1.1.1.1 | ip route add 10.9.0.0/16 via 10.0.0.1 |
| macOS | netstat -rn | route -n get 1.1.1.1 | sudo route -n add -net 10.9.0.0/16 10.0.0.1 |
| Windows | route print | Find-NetRoute -RemoteIPAddress 1.1.1.1 | route add 10.9.0.0 mask 255.255.0.0 10.0.0.1 |
| AWS | VPC route table | Reachability Analyzer | Route table entry (local, igw-, nat-, pcx-, tgw-) |
| Kubernetes node | ip route (per-node pod CIDR routes) | ip route get <pod-ip> | CNI writes them |
Real scenario: a corporate VPN pushes 10.0.0.0/8 and your Docker network on 10.250.0.0/24 becomes unreachable from the host, or the other way round; a laptop on both Ethernet and Wi-Fi uses Ethernet because of a lower metric; traffic to 10.96.0.10 (a Kubernetes Service) goes to the internet gateway because nobody added a route.
Fix: ip route get <dst> / route -n get <dst> first, always. The Go lpm snippet is a 30-line model of the lookup.
How a packet leaves your laptop Must-know
In plain words: routing table → "is it on my link?" → if yes, ARP for the destination; if no, ARP for the gateway → put the IP packet in a frame addressed to that MAC.
Common misunderstanding: "The packet's destination IP changes at each router." It does not (NAT aside); only the frame's destination MAC changes hop by hop. That is why traceroute can show every router while the IP header still names the server.
connect() from 10.0.0.25/24 (gateway 10.0.0.1)
1 app connect(10.0.0.80:5432) -> route 10.0.0.0/24 scope link
2 kernel neighbor cache miss -> ARP who-has 10.0.0.80 (broadcast)
3 kernel reply 10.0.0.80 is-at aa:.. -> frame dst MAC = server, IP dst = server
4 app connect(93.184.215.14:443) -> route 0.0.0.0/0 via 10.0.0.1
5 kernel ARP who-has 10.0.0.1 -> frame dst MAC = router, IP dst = 93.184.215.14
6 router decrements TTL, looks up its own table, re-frames for the next link| Error | errno | Means |
|---|---|---|
Network is unreachable | ENETUNREACH | No route matched (no default route) |
No route to host | EHOSTUNREACH | Route exists but ARP/NDP got no answer, or an ICMP host-unreachable came back |
Cannot assign requested address | EADDRNOTAVAIL | You tried to bind/source an IP the host does not own |
Connection refused | ECONNREFUSED | The host answered, nothing listens on that address:port (see Binding) |
| Timeout | ETIMEDOUT | Packets dropped silently: firewall, wrong route, asymmetric routing |
Real scenario: a container gets No route to host to a database because the DB's security group drops packets and the node's ARP entry for the gateway is fine; Network is unreachable in a container started with --network none.
Fix: read the errno before guessing; full playbook in Network Troubleshooting.
Binding and listening addresses Must-know
In plain words: a server picks which of the host's addresses it listens on. 127.0.0.1 is "only me", 0.0.0.0 is "every IPv4 address", [::] is "every address" (and usually IPv4 too), a specific IP is "only that network card".
Common misunderstanding: "My app works on localhost, so it will work in Docker." In a container, 127.0.0.1 is the container's own loopback. Docker's port publishing arrives on the container's eth0 address, where nothing listens.
Definition: bind() selects the local address. INADDR_ANY (0.0.0.0) and in6addr_any (::) mean all addresses. A socket on :: with IPV6_V6ONLY off also accepts IPv4 peers as IPv4-mapped addresses (::ffff:a.b.c.d). The Linux man page: "If this flag is set to false (zero), then the socket can be used to send and receive packets to and from an IPv6 address or an IPv4-mapped IPv6 address. The default value for this flag is defined by the contents of the file /proc/sys/net/ipv6/bindv6only." Go's net.Listen docs: "if the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available unicast and anycast IP addresses of the local system. To only use IPv4, use network "tcp4"."
Real output of the listen snippet (macOS; the Linux run in golang:1.24-alpine prints the same yes/no matrix):
$ go run ./listen
tcp 127.0.0.1:0 -> 127.0.0.1:55930 v4:yes v6:no
tcp [::1]:0 -> [::1]:55935 v4:no v6:yes
tcp4 0.0.0.0:0 -> 0.0.0.0:55938 v4:yes v6:no
tcp [::]:0 -> [::]:55941 v4:yes v6:yes
tcp6 [::]:0 -> [::]:55944 v4:no v6:yesThe Docker bind bug, reproduced on Docker Desktop for Mac (nc listening inside the container, -p 18080:8080 vs -p 18081:8080):
$ curl http://127.0.0.1:18080/ # app bound to 127.0.0.1 inside the container
curl: (56) Recv failure: Connection reset by peer
$ curl http://127.0.0.1:18081/ # app bound to 0.0.0.0
hi
$ docker exec bindbad netstat -tln
tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN
# from another container on the same network (the native Linux symptom):
wget: can't connect to remote host (10.250.0.5): Connection refused| Bind address | Reachable from same host | From other containers/hosts | Typical use |
|---|---|---|---|
127.0.0.1 / ::1 | Yes (same namespace only) | No | Admin ports, a sidecar-only port, local dev DB |
0.0.0.0 | Yes | Yes (IPv4) | Containers, servers behind a firewall |
[::] with v6only=0 | Yes | Yes (IPv4 + IPv6) | Default for Go ":8080", nginx listen [::]:80 + ipv6only=off |
Specific IP (10.0.1.5) | Via that IP | Only via that interface | Multi-homed hosts, keepalived VIPs |
Docker -p 127.0.0.1:5432:5432 | Host only | No | Publish a dev DB without exposing it on the LAN |
Real scenario: php artisan serve defaults to 127.0.0.1:8000, so in a container you need --host=0.0.0.0; Vite dev server needs --host; a Redis with bind 127.0.0.1 in a container that the app container cannot reach; a database published with -p 5432:5432 on a laptop in a café is reachable by everyone on the Wi-Fi (Docker publishes on all host addresses by default).
Fix: read the bind address from configuration with an all-interfaces default inside images (ADDR=:8080), publish dev databases on 127.0.0.1 on the host side, and verify with ss -ltn / netstat -tln. Deeper socket detail is in Ports, Sockets & Connections.
Cloud VPC addressing Important
In plain words: a VPC is your own private IP block in the cloud, split into subnets per availability zone. Route tables decide whether a subnet is public (default route to an Internet Gateway) or private (default route to a NAT gateway or nowhere).
Common misunderstanding: "A public subnet is one with public IPs." On AWS a subnet is public because its route table has 0.0.0.0/0 → igw-.... Instances also need a public or Elastic IP, which the Internet Gateway maps 1:1.
Definition (AWS): "The allowed IPv4 CIDR block size for a subnet is between a /28 netmask and /16 netmask." "The first four IP addresses and the last IP address in each subnet CIDR block are not available for your use": network (.0), VPC router (.1), DNS (.2, "the base of the VPC network range plus two"), reserved (.3), and broadcast (.255), because "We do not support broadcast in a VPC". AWS also canonicalises CIDRs: "if you specify 100.68.0.18/18 for the CIDR block, we create a CIDR block of 100.68.0.0/18." GCP subnets are regional, use any RFC 1918, CGNAT or privately-used public range, can be expanded later, and also reserve addresses in each primary range (network, gateway, second-to-last, broadcast). GCP's page refused automated fetching while this chapter was written, so check cloud.google.com/vpc/docs/subnets before relying on GCP numbers.
A private-subnet pod calls an external API on AWS
1 pod 10.0.130.7 -> route table of private-a: 0.0.0.0/0 -> nat-0abc (in public-a)
2 NAT gateway rewrites source to its Elastic IP, sends to igw-0def
3 IGW forwards to the internet; reply comes back to the Elastic IP
4 NAT gateway reverses the translation -> 10.0.130.7| Item | AWS | GCP | Kubernetes on either |
|---|---|---|---|
| Network scope | VPC per region, subnet per AZ | VPC global, subnet per region | Cluster inside the VPC |
| Size limits | VPC and subnet /16 to /28 | Primary ranges sized freely within limits (check docs) | Pod/Service CIDRs set at creation |
| Reserved per subnet | 5 (.0 .1 .2 .3 + last) | Several (check docs) | Service CIDR first IP = kubernetes Service |
| Internet egress | IGW (public) or NAT gateway (private) | Cloud NAT | Node or NAT gateway |
| Private service access | VPC endpoints | Private Google Access | n/a |
| Joining VPCs | Peering, Transit Gateway (no overlapping CIDRs) | VPC Peering, Shared VPC | Same rule: ranges must not overlap |
Real scenario: two teams both used 10.0.0.0/16 and now cannot peer their VPCs; a /24 node subnet on EKS with the VPC CNI runs out because each pod takes a VPC IP; an app hard-codes 10.0.0.2 as DNS and breaks in a VPC with a different base.
Fix: allocate VPC blocks from one company-wide plan, size subnets for pods if the CNI is VPC-native, and use the overlap checker in CI (Overlapping CIDRs). Firewall rules are in Firewalls; network segmentation design in DDoS Protection, Firewalls & VPCs.
Container and Kubernetes address planning Important
In plain words: Docker and Kubernetes create their own private networks on top of your host or VPC network. Their ranges must not collide with anything the hosts need to reach: the VPC, peered VPCs, the office VPN.
Common misunderstanding: "Container ranges are internal, so they cannot conflict." They create routes on the host. If Docker takes 192.168.0.0/20 and your office VPN is 192.168.1.0/24, the host's more specific or local route steals the traffic.
Definition:
- Docker: "When no --subnet option is provided, Docker automatically selects a subnet from predefined "default address pools"." Built-in pools:
172.17.0.0/16,172.18.0.0/16,172.19.0.0/16,172.20.0.0/14,172.24.0.0/14,172.28.0.0/14in /16 pieces and192.168.0.0/16in /20 pieces. The default bridge is172.17.0.0/16with gateway172.17.0.1. Compose creates<project-name>_defaultper project, each taking a new subnet from the pools. Change the pools in/etc/docker/daemon.json("default-address-pools": [{"base":"10.200.0.0/16","size":24}]), which the docs say allows "Docker to create 256 networks" from a /16. - Kubernetes: "Kubernetes clusters require to allocate non-overlapping IP addresses for Pods, Services and Nodes". The kube-apiserver
--service-cluster-ip-range"must not overlap with any IP ranges assigned to nodes or pods"; kubeadm's--service-cidrdefault is10.96.0.0/12. The cluster CIDR (--cluster-cidr, kubeadm--pod-network-cidr) is split into one node CIDR per node by--node-cidr-mask-size, "Default is 24 for IPv4 and 64 for IPv6"; the kubelet's--max-podsdefault is 110, and the scalability guide says "No more than 110 pods per node".
Sizing a pod CIDR
1 nodes you will ever have 200
2 per-node block (/24) 256 addresses, 110 pods max
3 blocks needed 200 -> round up to 256 = 2^8
4 cluster CIDR /24 - 8 = /16 (e.g. 10.244.0.0/16)
5 a /17 instead 128 nodes, then node 129 gets no pod CIDR| Product | Default range | Where you change it |
|---|---|---|
| Docker default bridge | 172.17.0.0/16 | daemon.json bip |
| Docker user networks / Compose | Pools from 172.17.0.0/16 ... 192.168.0.0/16 | default-address-pools, networks.ipam.config in Compose |
| Docker IPv6 | ULA prefix when no pool given | default-address-pools with an IPv6 base |
| kubeadm Service CIDR | 10.96.0.0/12 | --service-cidr |
| kubeadm pod CIDR | none (you choose; Flannel docs use 10.244.0.0/16) | --pod-network-cidr |
| Node CIDR mask | /24 IPv4, /64 IPv6 | --node-cidr-mask-size |
| EKS VPC CNI | Pods take VPC subnet IPs | Secondary CIDRs, custom networking with 100.64.0.0/10, prefix delegation |
Real scenario: a developer on a hotel Wi-Fi in 172.18.0.0/16 cannot reach anything because Compose already created 172.18.0.0/16; a cluster with /24 per node and a /20 cluster CIDR stops scheduling at node 17 (IP exhaustion); EKS nodes in a /24 subnet with VPC CNI and 30 pods each run out after about eight nodes.
Fix: reserve container ranges in the company plan (for example 10.200.0.0/16 for Docker hosts, 10.244.0.0/14 for pods, 10.96.0.0/12 for Services) and test with the overlap checker. The networking models themselves are in Docker Networking and Kubernetes Networking.
IPs in databases and logs Important
In plain words: store IPs as IPs, not strings, so you can ask "is this address inside that network?" with an index; and log the real client IP, which behind a proxy comes from a header you only trust from your own proxies.
Common misunderstanding: "X-Forwarded-For contains the client IP." It contains whatever the client sent plus what each proxy appended. Only the entries added by proxies you trust are real; the leftmost value is attacker-controlled.
Definition: PostgreSQL: "The inet type holds an IPv4 or IPv6 host address, and optionally its subnet, all in one field." "The essential difference between inet and cidr data types is that inet accepts values with nonzero bits to the right of the netmask, whereas cidr does not." Operators: << (is contained by), <<=, >>, >>= (contains or equals), && (overlaps); functions network(), broadcast(), host(), masklen(), netmask(), set_masklen(); GiST index with the inet_ops operator class. Laravel's ipAddress() "creates a VARCHAR equivalent column" and "When using PostgreSQL, an INET column will be created." X-Forwarded-For is a de facto header; RFC 7239 standardises Forwarded: for=....
Real session on postgres:18-alpine:
SELECT '10.0.12.7/20'::inet AS host_with_mask, network('10.0.12.7/20'::inet),
broadcast('10.0.12.7/20'::inet), host('10.0.12.7/20'::inet),
masklen('10.0.12.7/20'::inet), netmask('10.0.12.7/20'::inet);
-- host_with_mask | network | broadcast | host | masklen | netmask
-- 10.0.12.7/20 | 10.0.0.0/20 | 10.0.15.255/20 | 10.0.12.7 | 20 | 255.255.240.0
SELECT '10.0.12.7'::inet << '10.0.0.0/20'::cidr AS inside,
'10.1.0.0/16'::cidr && '10.0.0.0/8'::cidr AS overlaps,
'2001:db8:0:0:0:0:2:1'::inet AS v6_canonical;
-- t | t | 2001:db8::2:1
SELECT '10.0.12.7/20'::cidr;
-- ERROR: invalid cidr value: "10.0.12.7/20"
-- DETAIL: Value has bits set to right of mask.
SELECT set_masklen('203.0.113.77'::inet, 24)::cidr, set_masklen('2001:db8:abcd:12::99'::inet, 64)::cidr;
-- 203.0.113.0/24 | 2001:db8:abcd:12::/64
CREATE TABLE blocklist(id serial, network cidr NOT NULL);
CREATE INDEX ON blocklist USING gist (network inet_ops);
-- 60,001 /24 rows later:
EXPLAIN (COSTS OFF) SELECT id FROM blocklist WHERE network >>= '10.7.12.99'::inet;
-- Index Scan using blocklist_network_idx on blocklist
-- Index Cond: ((network)::inet >>= '10.7.12.99'::inet)Stored sizes (pg_column_size of a table column): 7 bytes for an IPv4 inet, 19 for IPv6.
| Database | Native type | Containment query | Index |
|---|---|---|---|
| PostgreSQL | inet, cidr, macaddr | net >>= ip | GiST/SP-GiST inet_ops, B-tree for equality |
| MySQL 8 | none: VARBINARY(16) + INET6_ATON() | ip BETWEEN start AND end | B-tree on start/end |
| SQLite | none: text or blob | application side | B-tree on blob |
| ClickHouse | IPv4, IPv6 | isIPAddressInRange() | primary key / skip index |
| Redis | none | sorted set by integer start (ZRANGEBYSCORE) | sorted set |
GeoIP: country/ASN lookups (MaxMind GeoLite2, IP2Location) are longest-prefix lookups on the client IP; they are only as good as the IP you feed them, so resolve the client through trusted proxies first, and never geolocate RFC 1918 or CGNAT addresses. Anycast and GeoDNS are in IP, DNS & GeoDNS.
Real scenario: an audit log full of 10.0.5.20 (the load balancer); a login rate limiter bypassed by sending X-Forwarded-For: 1.2.3.4; a fraud rule "block 203.0.113.0/24" implemented with LIKE '203.0.113.%'.
Fix: trusted-proxy resolution in Go and Laravel, an inet/cidr schema with a GiST index (Storing IPs), and rate limits per /24 and /64 (Rate limiting by subnet). Proxy design is in Forward vs Reverse Proxies.
Per-tool and per-platform behaviour
| Tool | Platform | What it answers | Example |
|---|---|---|---|
ip addr / ip -br addr | Linux (iproute2) | Addresses per interface | ip -4 addr show eth0 |
ifconfig | macOS, BSD, old Linux | Same | ifconfig en0 |
ip route, ip -6 route | Linux | Routing table | ip route show table all |
ip route get | Linux | Route + source for one destination | ip route get 1.1.1.1 |
ip rule | Linux | Policy routing rules | ip rule show |
netstat -rn, route -n get | macOS | Table, single lookup | route -n get default |
ip neigh | Linux | ARP/NDP cache with states | ip -s neigh |
arp -a / arp -an | macOS, Windows, Linux (net-tools) | ARP cache | arp -an |
ndp -an | macOS | IPv6 neighbor cache | ndp -an |
ping, ping6 / ping -6 | all | Reachability (ICMP) | ping6 ::1 |
traceroute, traceroute6, mtr, tracert | all | Hops (TTL expiry) | traceroute -n 1.1.1.1 |
ipcalc | Linux packages (Alpine/Debian differ) | Subnet math | ipcalc 10.0.12.7/20 |
sipcalc | Linux, Homebrew | Subnet math incl. IPv6 expansion | sipcalc 2001:db8::/64 |
tcpdump -e | all | Frames incl. MAC, ARP, NDP | tcpdump -nn -e arp |
Go net/netip | Go 1.18+ | Parse, contains, overlaps | netip.MustParsePrefix(...).Contains(a) |
PHP filter_var / inet_pton | PHP | Validate, pack | filter_var($ip, FILTER_VALIDATE_IP) |
Real sipcalc IPv6 output:
$ sipcalc 2001:db8:abcd:12::/64
Expanded Address - 2001:0db8:abcd:0012:0000:0000:0000:0000
Compressed address - 2001:db8:abcd:12::
Prefix address - ffff:ffff:ffff:ffff:0:0:0:0
Prefix length - 64
Network range - 2001:0db8:abcd:0012:0000:0000:0000:0000 -
2001:0db8:abcd:0012:ffff:ffff:ffff:ffff| Language / framework | Parse | Contains | Notes |
|---|---|---|---|
Go net/netip | ParseAddr, ParsePrefix | Prefix.Contains, Prefix.Overlaps | Value types, comparable, map keys; Unmap() for ::ffff: |
Go net (old) | net.ParseIP, net.ParseCIDR | IPNet.Contains | Slices, not comparable; prefer netip |
| PHP | inet_pton, filter_var | Byte masks (see SubnetMath) | FILTER_FLAG_NO_PRIV_RANGE, NO_RES_RANGE, GLOBAL_RANGE |
| Laravel 13 | ip, ipv4, ipv6, Rule::ip()->version(6) | Symfony IpUtils::checkIp() (used by TrustProxies) | $request->ip() respects trusted proxies |
| Python | ipaddress.ip_network | addr in net, net.overlaps() | strict=False to allow host bits |
| PostgreSQL | inet, cidr | >>=, && | GiST inet_ops |
Mechanics
Bitwise rules
network = addr & mask
broadcast = addr | ~mask
contains = (ip & mask) == (network & mask)
overlap = the shorter prefix contains the network of the longer one
block = 2^(32 - n); children of /n at /m = 2^(m - n)The PHP SubnetMath class applies exactly these on inet_pton() byte strings (&, |, ~ work bytewise on strings), and Go's netip.Prefix.Masked() / Overlaps() do the same internally.
ARP packet, byte by byte
RFC 826 lays the packet out as hardware type, protocol type, hardware length, protocol length, opcode, then sender and target addresses. The request captured above, decoded:
| Bytes (hex) | Field | Value |
|---|---|---|
ffff ffff ffff | Ethernet destination | Broadcast |
3656 d7eb 9586 | Ethernet source | Asking container |
0806 | EtherType | ARP |
0001 | Hardware type (ar$hrd) | Ethernet (1) |
0800 | Protocol type (ar$pro) | IPv4 |
06 / 04 | Hardware / protocol address length | 6 / 4 bytes |
0001 | Opcode | 1 = request (2 = reply) |
3656 d7eb 9586 | Sender MAC | 36:56:d7:eb:95:86 |
0afa 0004 | Sender IP | 10.250.0.4 |
0000 0000 0000 | Target MAC | Unknown yet |
0afa 0003 | Target IP | 10.250.0.3 |
Neighbor states (Linux)
| State | Meaning (ip-neighbour(8)) | What you do |
|---|---|---|
INCOMPLETE | Resolution in progress | Wait; persistent = host down or wrong subnet |
REACHABLE | Confirmed recently | Fine |
STALE | Valid but suspicious; will be re-checked on use | Normal for idle peers |
DELAY / PROBE | Re-confirmation in progress | Transient |
FAILED | No answer | Wrong IP, host down, VLAN/security group mismatch |
PERMANENT / NOARP | Static entry / no resolution needed | Set by admin or interface type |
Knobs
| Knob | Default | Effect |
|---|---|---|
net.ipv4.ip_forward | 0 (Docker/Kubernetes set 1) | Host routes packets between interfaces |
net.ipv6.bindv6only | 0 | :: sockets also accept IPv4-mapped peers |
net.ipv4.conf.*.arp_ignore / arp_announce | 0 | Which ARP requests to answer; needed for LVS/VIP setups |
net.ipv4.neigh.default.gc_thresh1/2/3 | 128/512/1024 | Neighbor table size; raise on large flat networks and big Kubernetes nodes |
net.ipv6.conf.*.accept_ra | 1 | Accept Router Advertisements |
net.ipv6.conf.*.use_tempaddr | distro-dependent | Privacy (temporary) addresses |
Docker bip, default-address-pools | 172.17.0.1/16, built-in pools | Container ranges |
kube --cluster-cidr, --service-cluster-ip-range, --node-cidr-mask-size | none, none (kubeadm 10.96.0.0/12), 24/64 | Cluster ranges |
When the neighbor table overflows (gc_thresh3), the kernel logs neighbour: arp_cache: neighbor table overflow! and new connections fail intermittently.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Subnet math by hand | Calculator in code | netip / SubnetMath | No off-by-one | None |
| Overlapping CIDRs | Overlap check in CI | Prefix.Overlaps, PostgreSQL && | Catches peering/VPN conflicts before deploy | Needs one source of truth |
| App unreachable in Docker | Bind 0.0.0.0/[::] from config | ADDR=:8080 | Works in every runtime | Expose only via published ports/firewall |
| Wrong client IP | Trusted-proxy walk | Right-to-left over XFF, stop at first untrusted | Spoof-proof | Must list LB subnets, both families |
| Querying "is IP in a blocked net?" | cidr + GiST | network >>= ip | Index scan | PostgreSQL only; MySQL needs ranges |
| IPv6 rate-limit bypass | Key by /64 (and /24) | RateKey | One customer = one bucket | CGNAT shares IPv4 /24s; keep limits generous |
| SSRF to metadata/private ranges | Reject non-global targets | FILTER_FLAG_GLOBAL_RANGE, classifier | Blocks 169.254.169.254 | Resolve DNS first and check the resolved IP |
| Pod IP exhaustion | Size cluster CIDR from max nodes | /n = node_mask - log2(nodes) | Predictable growth | Hard to change later |
Subnet calculator (Go and PHP)
// Command subnetcalc prints the subnet math for an IPv4 or IPv6 prefix,
// splits it into smaller subnets, and checks a list of prefixes for overlaps.
//
// go run ./subnetcalc 10.0.12.7/20
// go run ./subnetcalc -split 18 10.0.0.0/16
// go run ./subnetcalc -overlap 10.0.0.0/16,10.0.128.0/17,172.17.0.0/16
package main
import (
"flag"
"fmt"
"math/big"
"net/netip"
"os"
"strings"
)
func main() {
split := flag.Int("split", 0, "split the prefix into subnets of this length")
overlap := flag.String("overlap", "", "comma-separated prefixes to check for overlaps")
flag.Parse()
if *overlap != "" {
os.Exit(checkOverlaps(strings.Split(*overlap, ",")))
}
if flag.NArg() != 1 {
fmt.Fprintln(os.Stderr, "usage: subnetcalc [-split N] <addr/len>")
os.Exit(2)
}
p, err := netip.ParsePrefix(flag.Arg(0))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if *split > 0 {
subs, err := Split(p, *split)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
for i, s := range subs {
if i == 8 && len(subs) > 10 {
fmt.Printf("... %d more\n", len(subs)-9)
s = subs[len(subs)-1]
} else if i > 8 && len(subs) > 10 {
continue
}
fmt.Println(s)
}
return
}
Describe(os.Stdout, p)
}
// Info is the classic subnet-calculator answer for one prefix.
type Info struct {
Input netip.Prefix
Network netip.Prefix // masked prefix, e.g. 10.0.0.0/20
First netip.Addr // network address (all host bits 0)
Last netip.Addr // broadcast for IPv4 (all host bits 1)
Total *big.Int // 2^(bits-len)
Usable *big.Int // hosts you can assign on a classic LAN
FirstHost netip.Addr
LastHost netip.Addr
}
// Calc computes Info. It follows RFC 3021 for /31 (both addresses usable)
// and treats /32 and /128 as a single host.
func Calc(p netip.Prefix) Info {
n := p.Masked()
bits := n.Addr().BitLen()
hostBits := bits - n.Bits()
total := new(big.Int).Lsh(big.NewInt(1), uint(hostBits))
last := lastAddr(n)
info := Info{Input: p, Network: n, First: n.Addr(), Last: last, Total: total}
switch {
case hostBits == 0:
info.Usable, info.FirstHost, info.LastHost = big.NewInt(1), n.Addr(), n.Addr()
case n.Addr().Is4() && hostBits == 1:
info.Usable, info.FirstHost, info.LastHost = big.NewInt(2), n.Addr(), last
case n.Addr().Is4():
info.Usable = new(big.Int).Sub(total, big.NewInt(2))
info.FirstHost, info.LastHost = n.Addr().Next(), last.Prev()
default: // IPv6 has no broadcast; ::0 of the subnet is the Subnet-Router anycast (RFC 4291)
info.Usable, info.FirstHost, info.LastHost = total, n.Addr(), last
}
return info
}
// lastAddr sets every host bit to 1.
func lastAddr(p netip.Prefix) netip.Addr {
b := p.Addr().AsSlice()
for i := p.Bits(); i < len(b)*8; i++ {
b[i/8] |= 0x80 >> (i % 8)
}
a, _ := netip.AddrFromSlice(b)
return a
}
// Mask returns the dotted-quad netmask of an IPv4 prefix (255.255.240.0 for /20).
func Mask(p netip.Prefix) string {
m := uint32(0xffffffff) << (32 - p.Bits())
if p.Bits() == 0 {
m = 0
}
return fmt.Sprintf("%d.%d.%d.%d", byte(m>>24), byte(m>>16), byte(m>>8), byte(m))
}
// Describe prints Info the way ipcalc does.
func Describe(w *os.File, p netip.Prefix) {
i := Calc(p)
fmt.Fprintf(w, "input %s\n", i.Input)
fmt.Fprintf(w, "network %s\n", i.Network)
if p.Addr().Is4() {
fmt.Fprintf(w, "netmask %s\n", Mask(i.Network))
if i.Network.Bits() >= 31 {
fmt.Fprintf(w, "broadcast none (/31 point-to-point or /32 host)\n")
} else {
fmt.Fprintf(w, "broadcast %s\n", i.Last)
}
fmt.Fprintf(w, "binary %s\n", binary(i.Input.Addr(), i.Network.Bits()))
} else {
fmt.Fprintf(w, "last %s\n", i.Last)
}
fmt.Fprintf(w, "hosts %s .. %s\n", i.FirstHost, i.LastHost)
fmt.Fprintf(w, "total %s\n", i.Total)
fmt.Fprintf(w, "usable %s\n", i.Usable)
}
// binary renders an IPv4 address with a '|' at the prefix boundary.
func binary(a netip.Addr, bits int) string {
var sb strings.Builder
for i, b := range a.AsSlice() {
for j := 7; j >= 0; j-- {
if i*8+(7-j) == bits {
sb.WriteByte('|')
}
sb.WriteByte('0' + (b>>j)&1)
}
if i < 3 {
sb.WriteByte('.')
}
}
return sb.String()
}
// Split divides p into consecutive subnets of length newBits (VLSM building block).
func Split(p netip.Prefix, newBits int) ([]netip.Prefix, error) {
p = p.Masked()
if newBits < p.Bits() || newBits > p.Addr().BitLen() {
return nil, fmt.Errorf("cannot split %s into /%d", p, newBits)
}
if newBits-p.Bits() > 16 {
return nil, fmt.Errorf("refusing to list more than 65536 subnets")
}
var out []netip.Prefix
cur := netip.PrefixFrom(p.Addr(), newBits)
for p.Contains(cur.Addr()) {
out = append(out, cur)
next := lastAddr(cur).Next()
if !next.IsValid() {
break
}
cur = netip.PrefixFrom(next, newBits)
}
return out, nil
}
func checkOverlaps(list []string) int {
var ps []netip.Prefix
for _, s := range list {
p, err := netip.ParsePrefix(strings.TrimSpace(s))
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
ps = append(ps, p.Masked())
}
code := 0
for i := range ps {
for j := i + 1; j < len(ps); j++ {
if ps[i].Overlaps(ps[j]) {
fmt.Printf("OVERLAP %s and %s\n", ps[i], ps[j])
code = 1
}
}
}
if code == 0 {
fmt.Println("no overlaps")
}
return code
}<?php
declare(strict_types=1);
namespace App\Support\Net;
use InvalidArgumentException;
/**
* Subnet math for IPv4 and IPv6 on top of inet_pton(): no extensions needed.
* Works on packed binary strings (4 or 16 bytes), so both families share code.
*/
final class SubnetMath
{
/** @return array{0: string, 1: int} packed address and prefix length */
public static function parse(string $cidr): array
{
[$ip, $len] = array_pad(explode('/', $cidr, 2), 2, null);
$packed = @inet_pton((string) $ip);
if ($packed === false) {
throw new InvalidArgumentException("Not an IP address: {$ip}");
}
$max = strlen($packed) * 8;
$bits = $len === null ? $max : filter_var($len, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0, 'max_range' => $max],
]);
if ($bits === false) {
throw new InvalidArgumentException("Bad prefix length in {$cidr}");
}
return [$packed, $bits];
}
/** Packed mask with $bits leading one-bits, $bytes long. */
public static function mask(int $bits, int $bytes): string
{
$mask = str_repeat("\xff", intdiv($bits, 8));
if ($bits % 8 !== 0) {
$mask .= chr((0xff << (8 - $bits % 8)) & 0xff);
}
return str_pad($mask, $bytes, "\x00");
}
/** @return array{network: string, last: string, mask: string, total: string} */
public static function describe(string $cidr): array
{
[$packed, $bits] = self::parse($cidr);
$mask = self::mask($bits, strlen($packed));
$network = $packed & $mask;
$last = $network | ~$mask;
$hostBits = strlen($packed) * 8 - $bits;
return [
'network' => inet_ntop($network).'/'.$bits,
'last' => inet_ntop($last), // the IPv4 broadcast address
'mask' => strlen($packed) === 4 ? inet_ntop($mask) : '/'.$bits,
'total' => $hostBits < 63 ? (string) (1 << $hostBits) : "2^{$hostBits}",
];
}
public static function contains(string $cidr, string $ip): bool
{
[$net, $bits] = self::parse($cidr);
$addr = @inet_pton($ip);
if ($addr === false || strlen($addr) !== strlen($net)) {
return false; // different family never matches
}
$mask = self::mask($bits, strlen($net));
return ($addr & $mask) === ($net & $mask);
}
public static function overlaps(string $a, string $b): bool
{
[$na, $ba] = self::parse($a);
[$nb, $bb] = self::parse($b);
if (strlen($na) !== strlen($nb)) {
return false;
}
// Two prefixes overlap if the shorter one contains the longer one's network.
$mask = self::mask(min($ba, $bb), strlen($na));
return ($na & $mask) === ($nb & $mask);
}
/** Rate-limit bucket: /24 for IPv4, /64 for IPv6. */
public static function rateKey(string $ip): string
{
$packed = @inet_pton($ip);
if ($packed === false) {
return 'invalid';
}
// ::ffff:203.0.113.7 (IPv4-mapped, from a dual-stack socket) is really IPv4.
if (strlen($packed) === 16 && str_starts_with($packed, str_repeat("\x00", 10)."\xff\xff")) {
$packed = substr($packed, 12);
}
$bits = strlen($packed) === 4 ? 24 : 64;
return inet_ntop($packed & self::mask($bits, strlen($packed))).'/'.$bits;
}
}The PHP class run with php:8.5-cli-alpine (php demo.php) prints the same network, broadcast and mask as the Go tool:
Array
(
[network] => 10.0.0.0/20
[last] => 10.0.15.255
[mask] => 255.255.240.0
[total] => 4096
)
bool(true)
bool(true)
2001:db8:abcd:12::/64
203.0.113.0/24Overlapping CIDRs
$ go run ./subnetcalc -overlap 10.0.0.0/16,10.0.128.0/17,172.17.0.0/16
OVERLAP 10.0.0.0/16 and 10.0.128.0/17
exit status 1Run this in CI over every VPC, peered VPC, VPN, Docker pool and Kubernetes range in your plan. In PostgreSQL the same check is SELECT a.net, b.net FROM plan a JOIN plan b ON a.id < b.id AND a.net && b.net;.
Binding correctly
// Command listen shows which clients can reach a listener depending on the
// bind address: 127.0.0.1, ::1, 0.0.0.0, [::] (dual stack) or "tcp6" only.
//
// go run ./listen
// ADDR=0.0.0.0:8080 go run ./listen -serve # what a container must do
package main
import (
"flag"
"fmt"
"net"
"net/http"
"os"
"time"
)
type bind struct{ network, addr string }
func main() {
serve := flag.Bool("serve", false, "run an HTTP server on $ADDR (default :8080)")
flag.Parse()
if *serve {
runServer()
return
}
binds := []bind{
{"tcp", "127.0.0.1:0"}, // loopback only: invisible from other hosts/containers
{"tcp", "[::1]:0"}, // IPv6 loopback only
{"tcp4", "0.0.0.0:0"}, // every IPv4 address of this host
{"tcp", "[::]:0"}, // every address; dual stack (IPv4-mapped) where the OS allows
{"tcp6", "[::]:0"}, // IPv6 only (Go sets IPV6_V6ONLY)
}
for _, b := range binds {
ln, err := net.Listen(b.network, b.addr)
if err != nil {
fmt.Printf("%-5s %-12s listen error: %v\n", b.network, b.addr, err)
continue
}
go acceptLoop(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
fmt.Printf("%-5s %-12s -> %-16s v4:%-4s v6:%s\n", b.network, b.addr, ln.Addr(),
try(net.JoinHostPort("127.0.0.1", port)), try(net.JoinHostPort("::1", port)))
ln.Close()
}
}
func acceptLoop(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
return
}
c.Close()
}
}
// try dials the address and reports whether a TCP handshake completed.
func try(addr string) string {
c, err := net.DialTimeout("tcp", addr, 300*time.Millisecond)
if err != nil {
return "no"
}
c.Close()
return "yes"
}
// runServer is the container-friendly form: bind from config, default to all
// interfaces, never hard-code 127.0.0.1 inside an image.
func runServer() {
addr := os.Getenv("ADDR")
if addr == "" {
addr = ":8080" // empty host = all addresses, IPv4 and IPv6
}
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
host, _, _ := net.SplitHostPort(r.RemoteAddr)
fmt.Fprintf(w, "hello %s, you reached %s\n", host, r.Context().Value(http.LocalAddrContextKey))
})
srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
fmt.Println("listening on", addr)
if err := srv.ListenAndServe(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}For Laravel, the same rule applies to the process that serves PHP: php artisan serve --host=0.0.0.0 --port=8000, Octane --host=0.0.0.0, PHP-FPM listen = 0.0.0.0:9000 (or a Unix socket shared with nginx in the same pod).
Resolving the client IP behind proxies
// Command clientip resolves the real client IP behind trusted proxies,
// classifies addresses into the special ranges, and builds rate-limit keys
// per /24 (IPv4) or /64 (IPv6).
package main
import (
"fmt"
"net/netip"
"strings"
)
// Special ranges a backend meets most often (RFC 1918, 6598, 3927, 4193, 4291).
var special = []struct {
name string
prefix netip.Prefix
}{
{"rfc1918", netip.MustParsePrefix("10.0.0.0/8")},
{"rfc1918", netip.MustParsePrefix("172.16.0.0/12")},
{"rfc1918", netip.MustParsePrefix("192.168.0.0/16")},
{"cgnat", netip.MustParsePrefix("100.64.0.0/10")},
{"loopback", netip.MustParsePrefix("127.0.0.0/8")},
{"link-local", netip.MustParsePrefix("169.254.0.0/16")},
{"documentation", netip.MustParsePrefix("192.0.2.0/24")},
{"documentation", netip.MustParsePrefix("198.51.100.0/24")},
{"documentation", netip.MustParsePrefix("203.0.113.0/24")},
{"ula", netip.MustParsePrefix("fc00::/7")},
{"link-local", netip.MustParsePrefix("fe80::/10")},
{"documentation", netip.MustParsePrefix("2001:db8::/32")},
}
// Classify names the special range an address falls in, or "public".
func Classify(a netip.Addr) string {
a = a.Unmap() // ::ffff:10.1.2.3 must be treated as 10.1.2.3
for _, s := range special {
if s.prefix.Contains(a) {
return s.name
}
}
switch {
case a.IsLoopback():
return "loopback"
case a.IsMulticast():
return "multicast"
case a.IsUnspecified():
return "unspecified"
}
return "public"
}
// Trusted is the set of proxy networks whose X-Forwarded-For we believe.
type Trusted []netip.Prefix
func (t Trusted) contains(a netip.Addr) bool {
for _, p := range t {
if p.Contains(a.Unmap()) {
return true
}
}
return false
}
// ClientIP walks X-Forwarded-For from right to left and returns the first
// address that is not a trusted proxy. remote is the TCP peer address.
func (t Trusted) ClientIP(remote netip.Addr, xff string) netip.Addr {
if !t.contains(remote) || xff == "" {
return remote.Unmap() // direct client, or an untrusted hop: ignore the header
}
hops := strings.Split(xff, ",")
for i := len(hops) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
if err != nil {
return remote.Unmap() // garbage in the header: fall back to the peer
}
if !t.contains(a) {
return a.Unmap()
}
}
return remote.Unmap()
}
// RateKey groups clients by /24 for IPv4 and /64 for IPv6, because one IPv6
// host usually owns a whole /64 and can rotate addresses inside it freely.
func RateKey(a netip.Addr) string {
a = a.Unmap()
bits := 64
if a.Is4() {
bits = 24
}
p, _ := a.Prefix(bits)
return p.String()
}
func main() {
for _, s := range []string{"10.2.3.4", "100.72.1.9", "169.254.169.254", "fd12:3456::1",
"fe80::1", "::ffff:192.168.1.10", "8.8.8.8", "198.51.100.7", "224.0.0.251", "::"} {
fmt.Printf("%-22s %s\n", s, Classify(netip.MustParseAddr(s)))
}
trusted := Trusted{netip.MustParsePrefix("10.0.0.0/8")}
peer := netip.MustParseAddr("10.0.5.20") // the load balancer
fmt.Println(trusted.ClientIP(peer, "6.6.6.6, 198.51.100.7, 10.0.9.1"))
fmt.Println(trusted.ClientIP(netip.MustParseAddr("198.51.100.99"), "1.2.3.4"))
fmt.Println(RateKey(netip.MustParseAddr("198.51.100.77")))
fmt.Println(RateKey(netip.MustParseAddr("2001:db8:abcd:12:a1b2:c3d4:e5f6:789")))
}$ go run ./clientip (second part)
198.51.100.7 <- peer 10.0.5.20 is trusted; walk XFF right-to-left, skip 10.0.9.1
198.51.100.99 <- peer not trusted: ignore the header entirely
198.51.100.0/24
2001:db8:abcd:12::/64Laravel 13 does this through TrustProxies, configured in bootstrap/app.php ("Your trusted proxies should be specified using the trustProxies middleware method"). List CIDRs, not *, unless the app is only reachable through the load balancer:
<?php
// bootstrap/app.php (Laravel 13): trust only the load balancer subnets.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->trustProxies(
// The subnets your load balancers live in, never '*' on a host
// that is also reachable directly from the internet.
at: ['10.0.0.0/20', '10.0.16.0/20', 'fd00:10::/64'],
headers: Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_HOST
| Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO,
);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();Validating IPs and CIDRs in Laravel
Laravel's rules: ip ("must be an IP address"), ipv4, ipv6, and Rule::ip()->version(4|6). There is no CIDR rule, so a closure does it, and FILTER_FLAG_GLOBAL_RANGE rejects SSRF targets:
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use App\Support\Net\SubnetMath;
use Closure;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use InvalidArgumentException;
/**
* Validates an allow-list entry: a single address and a CIDR block.
* Laravel's ip/ipv4/ipv6 rules check single addresses only; a CIDR needs a closure.
*/
final class StoreFirewallRuleRequest extends FormRequest
{
public function rules(): array
{
return [
'peer_ip' => ['required', Rule::ip()], // 10.0.0.5 or 2001:db8::5
'office_ipv4' => ['nullable', 'ipv4'], // IPv4 only
'office_ipv6' => ['nullable', Rule::ip()->version(6)],
'network' => ['required', 'string', 'max:43', $this->cidr(...)],
'webhook_ip' => ['nullable', Rule::ip(), $this->publicOnly(...)],
];
}
/** 10.0.0.0/8 passes; 10.0.0.1/8 (host bits set) and 10.0.0.0/33 fail. */
private function cidr(string $attribute, mixed $value, Closure $fail): void
{
try {
$info = SubnetMath::describe((string) $value);
} catch (InvalidArgumentException) {
$fail("The {$attribute} must be a CIDR block such as 10.0.0.0/8.");
return;
}
if (! str_contains((string) $value, '/') || $info['network'] !== strtolower((string) $value)) {
$fail("The {$attribute} must be written as its network address ({$info['network']}).");
}
}
/** Blocks SSRF targets: RFC 1918, loopback, link-local (169.254.169.254), CGNAT, ULA... */
private function publicOnly(string $attribute, mixed $value, Closure $fail): void
{
if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE) === false) {
$fail("The {$attribute} must be a public, globally routable address.");
}
}
}What PHP's filter flags accept (real run, php filter-demo.php on PHP 8.5):
8.8.8.8 ip=yes noPriv=yes noRes=yes global=yes
10.1.2.3 ip=yes noPriv=no noRes=yes global=no
127.0.0.1 ip=yes noPriv=yes noRes=no global=no
169.254.169.254 ip=yes noPriv=yes noRes=no global=no
100.64.1.1 ip=yes noPriv=yes noRes=yes global=no
fd00::1 ip=yes noPriv=no noRes=yes global=no
::1 ip=yes noPriv=yes noRes=no global=no
2001:db8::1 ip=yes noPriv=yes noRes=yes global=no
[::1] ip=no noPriv=no noRes=no global=no
010.1.2.3 ip=no noPriv=no noRes=no global=noNote that NO_PRIV_RANGE alone lets 127.0.0.1, 169.254.169.254 and CGNAT through; use GLOBAL_RANGE.
Storing IPs
<?php
// database/migrations/2026_11_25_000000_create_access_logs_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('access_logs', function (Blueprint $table) {
$table->id();
// PostgreSQL: INET (7 bytes stored for IPv4, 19 for IPv6). Others: VARCHAR.
$table->ipAddress('client_ip')->index();
$table->string('forwarded_for', 512)->nullable(); // raw header, for audits only
$table->timestamp('created_at')->useCurrent();
});
Schema::create('ip_blocks', function (Blueprint $table) {
$table->id();
$table->string('reason');
});
if (DB::getDriverName() === 'pgsql') {
// cidr rejects host bits (10.0.0.1/8) at insert time; GiST makes >>= fast.
DB::statement('ALTER TABLE ip_blocks ADD COLUMN network cidr NOT NULL');
DB::statement('CREATE INDEX ip_blocks_network_gist ON ip_blocks USING gist (network inet_ops)');
} else {
// MySQL: store the packed range as VARBINARY(16) start/end and compare bytes.
Schema::table('ip_blocks', function (Blueprint $table) {
$table->binary('range_start', length: 16, fixed: false);
$table->binary('range_end', length: 16, fixed: false);
$table->index(['range_start', 'range_end']);
});
}
}
public function down(): void
{
Schema::dropIfExists('ip_blocks');
Schema::dropIfExists('access_logs');
}
};<?php
declare(strict_types=1);
namespace App\Support\Net;
use Illuminate\Support\Facades\DB;
/** Is this client inside any blocked network? One indexed query per request. */
final class IpBlockList
{
public function isBlocked(string $ip): bool
{
if (DB::getDriverName() === 'pgsql') {
// >>= is "contains or equals"; served by the GiST inet_ops index.
return DB::table('ip_blocks')
->whereRaw('network >>= ?::inet', [$ip])
->exists();
}
$packed = inet_pton($ip); // 4 or 16 raw bytes, compared bytewise
return DB::table('ip_blocks')
->where('range_start', '<=', $packed)
->where('range_end', '>=', $packed)
->whereRaw('LENGTH(range_start) = ?', [strlen($packed)])
->exists();
}
}Rate limiting by subnet
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Support\Net\SubnetMath;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// $request->ip() is already the real client because TrustProxies ran first.
RateLimiter::for('login', function (Request $request) {
$ip = (string) $request->ip();
return [
Limit::perMinute(10)->by('ip:'.$ip),
// One IPv6 customer owns a whole /64 and can rotate through it;
// a CGNAT /24 shares many users, so keep this limit generous.
Limit::perMinute(100)->by('net:'.SubnetMath::rateKey($ip)),
];
});
}
}The Go RateKey above produces the same keys. Algorithms are in Rate Limiting and Rate Limiting in Go.
Modelling the routing decision
// Command lpm is a toy routing table: longest-prefix match, then metric.
// It mirrors what `ip route get` and `route -n get` answer.
package main
import (
"fmt"
"net/netip"
)
// Route is one row of a routing table. Via is empty for on-link routes.
type Route struct {
Dst netip.Prefix
Via string
Dev string
Metric int
}
// Lookup returns the most specific matching route; ties go to the lowest metric.
func Lookup(table []Route, dst netip.Addr) (Route, bool) {
var best Route
found := false
for _, r := range table {
if !r.Dst.Contains(dst) {
continue
}
if !found || r.Dst.Bits() > best.Dst.Bits() ||
(r.Dst.Bits() == best.Dst.Bits() && r.Metric < best.Metric) {
best, found = r, true
}
}
return best, found
}
func main() {
table := []Route{
{netip.MustParsePrefix("0.0.0.0/0"), "192.168.1.1", "wlan0", 600}, // default gateway (Wi-Fi)
{netip.MustParsePrefix("0.0.0.0/0"), "10.20.0.1", "eth0", 100}, // default gateway (cable wins)
{netip.MustParsePrefix("192.168.1.0/24"), "", "wlan0", 600}, // on-link LAN
{netip.MustParsePrefix("10.20.0.0/16"), "", "eth0", 100}, // on-link office LAN
{netip.MustParsePrefix("10.0.0.0/8"), "10.8.0.1", "wg0", 50}, // VPN to the company
{netip.MustParsePrefix("172.17.0.0/16"), "", "docker0", 0}, // Docker bridge
{netip.MustParsePrefix("10.96.0.0/12"), "10.8.0.1", "wg0", 50}, // cluster Service CIDR via VPN
}
for _, d := range []string{"192.168.1.42", "10.20.3.4", "10.1.2.3", "10.96.0.10", "172.17.0.2", "1.1.1.1"} {
r, _ := Lookup(table, netip.MustParseAddr(d))
next := "on-link (ARP for " + d + ")"
if r.Via != "" {
next = "via " + r.Via + " (ARP for the gateway)"
}
if r.Dev == "wg0" {
next = "via " + r.Via + " (layer-3 tunnel: no ARP)"
}
fmt.Printf("%-13s -> %-15s dev %-7s %s\n", d, r.Dst, r.Dev, next)
}
}$ go run ./lpm
192.168.1.42 -> 192.168.1.0/24 dev wlan0 on-link (ARP for 192.168.1.42)
10.20.3.4 -> 10.20.0.0/16 dev eth0 on-link (ARP for 10.20.3.4)
10.1.2.3 -> 10.0.0.0/8 dev wg0 via 10.8.0.1 (layer-3 tunnel: no ARP)
10.96.0.10 -> 10.96.0.0/12 dev wg0 via 10.8.0.1 (layer-3 tunnel: no ARP)
172.17.0.2 -> 172.17.0.0/16 dev docker0 on-link (ARP for 172.17.0.2)
1.1.1.1 -> 0.0.0.0/0 dev eth0 via 10.20.0.1 (ARP for the gateway)Troubleshooting
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
curl: (56) Connection reset / Connection refused to a published port | App bound to 127.0.0.1 in the container | docker exec c netstat -tln | Bind 0.0.0.0 / [::] |
Container cannot reach a 192.168.x/172.x host on the VPN | Docker network overlaps the VPN range | ip route get <ip> on the host | default-address-pools, recreate networks |
Network is unreachable | No matching route (no default gateway) | ip route | Add default route / fix DHCP |
No route to host | ARP/NDP failed or ICMP unreachable | ip neigh shows FAILED | Correct subnet/VLAN, security group |
Address is 169.254.x.x | DHCP failed, link-local fallback | ip addr, DHCP logs | Fix DHCP reachability |
| VPC peering request rejected | Overlapping CIDRs | Overlap checker | Re-address one side, or use PrivateLink/NAT |
Pods stuck ContainerCreating, "no IP addresses available" | Node pod CIDR or VPC subnet exhausted | kubectl describe node, CNI logs | Bigger cluster CIDR, prefix delegation, secondary CIDR |
All requests appear from 10.0.x.x | Proxy not trusted | Log REMOTE_ADDR and XFF | trustProxies(at: [...]) |
| Rate limit bypassed with fake XFF | Trusting * on a directly reachable app | Send XFF with curl | Trust only LB CIDRs, firewall direct access |
| IPv6 works then stops on the LAN | ICMPv6 blocked, NDP broken | ip -6 neigh | Allow ICMPv6 133–137 |
| Clients talk to the old server after failover | Stale ARP caches | arp -an on clients | Send gratuitous ARP (keepalived does) |
cidr insert fails: "bits set to right of mask" | Host bits in a network value | Masked form | Insert network(x) or use inet |
Go net.Dial fails with "too many colons in address" | IPv6 without brackets | Print the address | net.JoinHostPort |
neighbor table overflow! in dmesg | Neighbor cache too small | count ip neigh lines | Raise gc_thresh* |
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| New AWS VPC per environment | /16 from a company plan (10.10/16, 10.20/16...) | Overlap check in CI | Peering and Transit Gateway need disjoint ranges |
| Public subnet (LB, NAT GW) | /24 per AZ | Few hosts, IGW route | Small, rarely grows |
| Private node subnet with VPC-native CNI | /19–/20 per AZ | Prefix delegation | Every pod consumes a VPC IP |
| Kubernetes pod CIDR (overlay CNI) | /16 for up to 256 nodes at /24 each | Outside the VPC and VPN ranges | 110 pods per node fit in /24 |
| Kubernetes Service CIDR | /16 or kubeadm /12 | Disjoint from everything | Virtual, but routed by kube-proxy |
| Docker hosts and laptops | Pools in a reserved 10.200.0.0/16, size /24 | daemon.json | Avoid hotel/VPN 172.x/192.168.x |
| Point-to-point link | /31 (IPv4), /127 (IPv6, RFC 6164) | n/a | No waste |
| One host in an allow-list or route | /32, /128 | n/a | Exact match |
| IPv6 LAN | Always /64 | SLAAC | Required by SLAAC, privacy addresses |
| IPv6 site | /56 or /48 | Plan by nibble boundaries | 256 or 65,536 subnets |
| Storing client IPs | PostgreSQL inet; MySQL VARBINARY(16) | GiST inet_ops | Containment queries with an index |
In architecture: from a single process to a distributed system
Everyday example: a Laravel shop on one VPS. Production example: the same shop grown into services on Kubernetes in two AWS regions.
Monolith (one process, one host)
The everyday shop: nginx on 0.0.0.0:443, PHP-FPM on 127.0.0.1:9000, MySQL on 127.0.0.1:3306. Loopback binds are correct here: they keep the database off the network without a firewall rule. The two IP decisions that matter are TrustProxies (if a CDN or LB sits in front, list its ranges) and storing $request->ip() in an ipAddress() column. Move the same app into Docker Compose and the loopback binds become the bind bug: every service must listen on 0.0.0.0 inside its container and talk to others by service name on <project>_default.
Modular monolith and multiple databases
Two or three hosts in one VPC: app servers in private /20s, a database subnet /24 per AZ, a load balancer in public /24s. Address planning becomes a module boundary: the database subnet's security group allows only the app subnet's CIDR. Read replicas get their own IPs; the app should use DNS names, not hard-coded IPs, so failover can move them. The everyday shop's admin panel is allowed only from the office /32.
Microservices
The production shop on Kubernetes: every pod has its own IP from the node's /24, Services get virtual IPs from the Service CIDR, and IPs change on every restart, so nothing stores pod IPs; service discovery is DNS. The client IP must survive the hops: CDN → AWS ALB (in 10.0.0.0/24 and 10.0.1.0/24) → ingress controller (pod IP) → service pods. Each hop appends to X-Forwarded-For; each service trusts only the previous hop's CIDR (ALB subnets for the ingress, pod CIDR for internal services) or, better, only the edge resolves the client IP and passes it as a signed header. NetworkPolicies and security groups are written as CIDRs and labels.
Client IP through the production path
1 client 198.51.100.7 -> CDN edge (anycast)
2 CDN 203.0.113.10 -> ALB 10.0.0.37 XFF: 198.51.100.7
3 ALB -> ingress pod 10.0.130.4 XFF: 198.51.100.7, 203.0.113.10
4 ingress (trusts ALB /24s) resolves 198.51.100.7, forwards to orders pod 10.0.131.9
5 orders (trusts pod CIDR 10.0.128.0/17) logs 198.51.100.7 in an inet columnDistributed data, multi-VPC and multi-region
Two regions mean two VPCs (10.10.0.0/16 eu, 10.20.0.0/16 us) joined by peering or Transit Gateway, plus pod and Service CIDRs per cluster that must also be unique if pods talk across clusters (multi-cluster meshes, Cilium Cluster Mesh). Database replication between regions runs over private IPs, so overlapping ranges make replication impossible without NAT. Caches and databases often allow-list replication peers by /32. IPv6 dual stack helps here: ULA or global /64s per subnet never run out. Anycast and GeoDNS route users to the nearest region (IP, DNS & GeoDNS); load balancing across regions is in Load Balancing.
Scaling path
| Load | Addressing change |
|---|---|
| 1× (one VPS) | Loopback binds, one public IP, trust the CDN ranges |
| 10× (a few hosts, one VPC) | /16 VPC from a plan, /20 private subnets, LB in public /24s, inet columns |
| 100× (Kubernetes, many teams) | Cluster CIDR sized for max nodes, prefix delegation or secondary CIDRs (100.64.0.0/10) when VPC IPs run out, IPAM tool (AWS VPC IPAM, NetBox), overlap check in CI |
| Multi-region | Region-unique blocks, Transit Gateway, dual stack, per-/64 rate limits at the edge |
Lab
Requirements: Docker, Go 1.24+, and optionally ipcalc/sipcalc (apk add ipcalc sipcalc inside Alpine).
Compute subnets by hand, then verify. On paper: network, broadcast, first, last and usable for
172.20.37.200/21,192.168.1.77/27,10.0.0.6/31. Then:bashcd docs/snippets/foundations/ip-addressing-subnets-cidr/go go run ./subnetcalc 172.20.37.200/21 # expect 172.20.32.0/21, broadcast 172.20.39.255, 2046 usable go run ./subnetcalc 192.168.1.77/27 # expect .64-.95, hosts .65-.94 go run ./subnetcalc -split 20 10.0.0.0/16 | head -3 go run ./subnetcalc -overlap 10.0.0.0/16,192.168.0.0/16,10.0.200.0/24Inspect your laptop. Linux:
ip -br addr; ip route; ip route get 1.1.1.1; ip neigh. macOS:ifconfig en0; netstat -rn -f inet; route -n get 1.1.1.1; arp -an; ndp -an. Find your default gateway, its MAC in the ARP cache, and any VPN routes that are longer than/0. Compareping -c1 127.0.0.2on macOS (no reply: only127.0.0.1is configured onlo0) and in a Linux container (reply: Linux routes the whole127.0.0.0/8tolo, seeip route show table local).Two containers and ARP.
bashdocker network create --subnet 10.250.0.0/24 ipnet-lab docker run -d --rm --name ipa --network ipnet-lab alpine:3.20 sleep 600 docker run -d --rm --name ipb --network ipnet-lab alpine:3.20 sleep 600 docker run -d --rm --name ipc --cap-add NET_ADMIN --network ipnet-lab alpine:3.20 sleep 600 docker exec ipc apk add -q tcpdump iproute2 docker exec ipc sh -c 'ip neigh flush dev eth0; tcpdump -i eth0 -nn -e -XX -c 3 arp & sleep 1; ping -c1 10.250.0.3; sleep 2' # expect: Request who-has 10.250.0.3 tell 10.250.0.4 ... Reply 10.250.0.3 is-at ... docker exec ipc ip route get 1.1.1.1 # 1.1.1.1 via 10.250.0.1 dev eth0 docker exec ipc ip -s neigh # 10.250.0.3 ... REACHABLEIPv6 and NDP.
docker network create --ipv6 --subnet fd00:ab:cd::/64 ipnet6-lab, start two containers, capturetcpdump -nn -e 'icmp6 and (ip6[40]==135 or ip6[40]==136)'whileping -6the other. Expect a neighbor solicitation toff02::1:ff00:3(MAC33:33:ff:00:00:03) and an advertisement back. Check the EUI-64 link-local address against the MAC.The 127.0.0.1 bind bug.
bashdocker run -d --rm --name bindbad -p 18080:8080 alpine:3.20 sh -c 'while true; do printf "HTTP/1.0 200 OK\r\n\r\nhi\n" | nc -l -s 127.0.0.1 -p 8080; done' docker run -d --rm --name bindgood -p 18081:8080 alpine:3.20 sh -c 'while true; do printf "HTTP/1.0 200 OK\r\n\r\nhi\n" | nc -l -s 0.0.0.0 -p 8080; done' curl http://127.0.0.1:18080/ # Docker Desktop: (56) reset by peer; Linux host: connection refused/reset curl http://127.0.0.1:18081/ # hi docker exec bindbad netstat -tlnThen run
go run ./listento see the same matrix for127.0.0.1,::1,0.0.0.0,[::]andtcp6.IPs in PostgreSQL.
docker run -d --rm --name ippg -e POSTGRES_PASSWORD=x postgres:18-alpine, then run the SQL session: try inserting10.0.12.7/20into acidrcolumn, build the GiST index, and confirmEXPLAINshows an index scan fornetwork >>= '10.7.12.99'.
Clean up: docker rm -f ipa ipb ipc bindbad bindgood ippg; docker network rm ipnet-lab ipnet6-lab.
Common misconceptions
| Belief | Reality |
|---|---|
| A /24 has 256 usable hosts | 254 on a LAN, 251 on AWS, 256 only as a pod range where the CNI decides |
172.x.x.x is private | Only 172.16.0.0/12 (172.16–172.31) |
100.64.x.x is a public client | CGNAT shared space; many users behind one address |
| Dots mark the network boundary | The prefix length does; /20 splits an octet |
| The first matching route wins | The longest prefix wins, then the metric |
| ARP finds the remote server's MAC | Only on-link; otherwise the gateway's MAC |
127.0.0.1 works inside Docker like on my laptop | It is the container's own loopback; bind 0.0.0.0 |
0.0.0.0 is a destination | It is "unspecified": a bind wildcard or the default route |
| IPv6 needs NAT for security | The firewall gives security; IPv6 rarely uses NAT |
| Blocking all ICMPv6 hardens IPv6 | It breaks NDP and PMTUD |
The leftmost X-Forwarded-For value is the client | It is client-controlled; walk from the right over trusted proxies |
| Container ranges cannot collide with anything | They install host routes and shadow VPN/LAN ranges |
| /31 is useless | RFC 3021: two usable addresses on point-to-point links |
| A per-IP rate limit works for IPv6 | One host can rotate through 2^64 addresses; key by /64 |
Cheat sheet
| Topic | Remember |
|---|---|
| Block size | 256 − mask octet; network = largest multiple ≤ address |
| Usable IPv4 hosts | 2^(32−n) − 2; /31 = 2, /32 = 1; AWS −5 |
| Private ranges | 10/8, 172.16/12, 192.168/16; CGNAT 100.64/10 |
| Loopback / link-local | 127/8, ::1; 169.254/16, fe80::/10 |
| ULA | fc00::/7, use fd00::/8 with a random 40-bit global ID |
| Documentation | 192.0.2/24, 198.51.100/24, 203.0.113/24, 2001:db8::/32 |
| IPv6 text | lowercase, :: once and as long as possible, [addr]:port |
| IPv6 sizes | /64 LAN, /56 home, /48 site |
| Routing | Longest prefix, then metric; ip route get / route -n get |
| On-link vs via | On-link: ARP the destination; via: ARP the gateway |
| ARP/NDP | ip neigh, arp -an, ndp -an; gratuitous ARP on failover |
| Bind | Containers: 0.0.0.0 or [::]; host-only: 127.0.0.1 |
| Kubernetes | Pod, Service, node ranges all disjoint; /24 per node, 110 pods |
| Docker | 172.17.0.0/16 default; set default-address-pools to avoid VPNs |
| Storage | PostgreSQL inet/cidr + GiST inet_ops; Laravel ipAddress() |
| Client IP | trustProxies(at: [LB CIDRs]), never * on a reachable app |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What are the network, broadcast and usable range of 10.4.77.130/26? Must-know
Answer
Answer: Block size 64 in the 4th octet; 130 is in 128–191. Network 10.4.77.128, broadcast 10.4.77.191, hosts .129–.190, 62 usable.
2 — Is 172.32.5.4 private? Must-know
Answer
Answer: No. RFC 1918's 172 block is 172.16.0.0–172.31.255.255; 172.32.x is public.
3 — Your laptop has default via 192.168.1.1 and a VPN route 10.0.0.0/8 dev utun4. Which interface carries 10.84.0.5, and which carries 8.8.8.8? Must-know
Answer
Answer: 10.84.0.5 matches /8 (longer than /0), so the VPN. 8.8.8.8 only matches the default, so Wi-Fi via 192.168.1.1.
4 — When you ping 1.1.1.1, whose MAC address does your laptop ARP for? Must-know
Answer
Answer: The default gateway's. The IP destination stays 1.1.1.1; only the frame goes to the router's MAC.
5 — Why does a container whose app listens on 127.0.0.1:8080 not answer docker run -p 8080:8080? Must-know
Answer
Answer: Published traffic arrives on the container's eth0 address; loopback in the container's namespace is unreachable from outside. Bind 0.0.0.0 or [::].
6 — How many /24 node CIDRs fit in a /18 cluster CIDR, and how many pods can the cluster hold at the default max-pods? Important
Answer
Answer: 2^(24−18) = 64 nodes; 64 × 110 = 7,040 pods.
7 — Write 2001:0db8:0000:0000:0001:0000:0000:0001 in canonical form. Important
Answer
Answer: 2001:db8::1:0:0:1. Both zero runs are two groups long; RFC 5952 compresses the first one.
8 — Which messages does IPv6 use instead of ARP, and where are they sent? Important
Answer
Answer: ICMPv6 Neighbor Solicitation (135) to the solicited-node multicast ff02::1:ffXX:XXXX, answered by Neighbor Advertisement (136).
9 — A request reaches your app from 10.0.5.20 with X-Forwarded-For: 6.6.6.6, 198.51.100.7, 10.0.9.1. Trusted: 10.0.0.0/8. What is the client IP? Important
Answer
Answer: 198.51.100.7: walk from the right, skip trusted 10.0.9.1, stop at the first untrusted address. 6.6.6.6 was supplied by the client.
10 — Why can PostgreSQL store 10.0.12.7/20 as inet but not as cidr? Good to know
Answer
Answer: cidr represents a network and rejects host bits to the right of the mask ("Value has bits set to right of mask"); inet is a host address with an optional mask.
11 — Why key an IPv6 rate limit by /64? Important
Answer
Answer: One subscriber or host typically owns a whole /64 and can use any address inside it, so a per-/128 limit is trivially bypassed.
12 — Two VPCs are 10.0.0.0/16 and 10.0.128.0/17. Can you peer them? Important
Answer
Answer: No: the /17 lies inside the /16, so the ranges overlap and AWS rejects peering with overlapping CIDRs.
Glossary
| Term | Meaning |
|---|---|
| IPv4 | 32-bit Internet Protocol address (RFC 791) |
| IPv6 | 128-bit Internet Protocol address (RFC 8200, RFC 4291) |
| Octet | 8 bits; one of the four numbers in a dotted quad |
| Dotted quad | Decimal text form of IPv4, 10.0.12.7 |
| Classful addressing | Pre-1993 Class A/B/C/D/E split by leading bits |
| CIDR | Classless Inter-Domain Routing; address/prefix-length notation (RFC 4632) |
| Prefix length | Number of leading network bits, the /n |
| Subnet mask | Prefix length written as a 32-bit mask, 255.255.240.0 |
| Wildcard mask | Inverted mask, 0.0.15.255; Cisco ACLs |
| Network address | First address of a block, all host bits 0 |
| Broadcast address | Last IPv4 address of a block, all host bits 1 |
| Limited broadcast | 255.255.255.255, this link only |
| Host route | A /32 or /128 route to a single address |
| VLSM | Variable Length Subnet Masking: subnets of different sizes from one block |
| RFC 1918 | The three private IPv4 blocks |
| CGNAT / Shared Address Space | 100.64.0.0/10, carrier-grade NAT (RFC 6598) |
| Loopback | 127.0.0.0/8 and ::1, never leave the host |
| Link-local | 169.254.0.0/16 and fe80::/10, valid on one link only |
| Multicast | One-to-many addresses, 224.0.0.0/4, ff00::/8 |
| Anycast | One address announced from many places; nearest one answers |
| Unspecified address | 0.0.0.0 / ::; bind wildcard or default route |
| ULA | Unique Local Address, fc00::/7 (RFC 4193) |
| Global unicast | Internet-routable IPv6, 2000::/3 |
| IPv4-mapped IPv6 | ::ffff:a.b.c.d, how dual-stack sockets show IPv4 peers |
| Zone ID | %en0 suffix choosing the interface for a link-local address |
| Interface ID | Low 64 bits of an IPv6 address |
| EUI-64 | Interface ID built from the MAC with ff:fe inserted |
| Privacy extensions | Random temporary IPv6 addresses (RFC 4941) |
| SLAAC | Stateless Address Autoconfiguration (RFC 4862) |
| DHCPv6 | Stateful/stateless IPv6 configuration and prefix delegation (RFC 8415) |
| Dual stack | IPv4 and IPv6 on the same interface/service |
| ARP | Address Resolution Protocol, IPv4 → MAC (RFC 826) |
| ARP cache / neighbor table | Kernel table of IP → MAC with states |
| Gratuitous ARP | Unsolicited ARP announcing one's own mapping |
| ARP spoofing | Forged ARP replies to intercept traffic |
| NDP | Neighbor Discovery Protocol for IPv6 (RFC 4861) |
| Solicited-node multicast | ff02::1:ffXX:XXXX group used by NS |
| Router Advertisement | ICMPv6 134; announces prefixes and the default router |
| DAD | Duplicate Address Detection |
| Routing table | List of prefixes with next hop, device and metric |
| Longest-prefix match | The most specific matching route wins |
| Default gateway | Next hop of 0.0.0.0/0 / ::/0 |
| On-link | Destination reachable directly on an attached link |
| Metric | Route preference; lower wins among equal prefixes |
| Policy routing | Choosing a routing table by source, mark or interface (ip rule) |
| VPC | Virtual Private Cloud, your private address block in a cloud |
| Internet Gateway (IGW) | AWS gateway that makes a subnet public |
| NAT gateway | Managed NAT for private subnets' outbound traffic |
| Pod CIDR / cluster CIDR | Range from which pod IPs are allocated |
| Node CIDR | One node's slice of the cluster CIDR |
| Service CIDR | Range for Kubernetes ClusterIPs |
| IP exhaustion | No free addresses left in a subnet or pod range |
inet / cidr | PostgreSQL types for host addresses and networks |
| X-Forwarded-For | De facto header listing the client and proxies |
| Trusted proxy | A proxy whose forwarding headers you believe |
| GeoIP | Mapping IP prefixes to locations/ASNs |
net/netip | Go package with value-type Addr and Prefix |
ipcalc / sipcalc | Command-line subnet calculators |
| ENETUNREACH / EHOSTUNREACH | "Network is unreachable" / "No route to host" |
References
- RFC 791, Internet Protocol: https://www.rfc-editor.org/rfc/rfc791
- RFC 826, An Ethernet Address Resolution Protocol: https://www.rfc-editor.org/rfc/rfc826
- RFC 919, Broadcasting Internet Datagrams: https://www.rfc-editor.org/rfc/rfc919
- RFC 1112, Host Extensions for IP Multicasting: https://www.rfc-editor.org/rfc/rfc1112
- RFC 1122, Requirements for Internet Hosts: https://www.rfc-editor.org/rfc/rfc1122
- RFC 1918, Address Allocation for Private Internets: https://www.rfc-editor.org/rfc/rfc1918
- RFC 3021, Using 31-Bit Prefixes on IPv4 Point-to-Point Links: https://www.rfc-editor.org/rfc/rfc3021
- RFC 3927, Dynamic Configuration of IPv4 Link-Local Addresses: https://www.rfc-editor.org/rfc/rfc3927
- RFC 4193, Unique Local IPv6 Unicast Addresses: https://www.rfc-editor.org/rfc/rfc4193
- RFC 4291, IP Version 6 Addressing Architecture: https://www.rfc-editor.org/rfc/rfc4291
- RFC 4632, Classless Inter-domain Routing (CIDR): https://www.rfc-editor.org/rfc/rfc4632
- RFC 4861, Neighbor Discovery for IPv6: https://www.rfc-editor.org/rfc/rfc4861
- RFC 4862, IPv6 Stateless Address Autoconfiguration: https://www.rfc-editor.org/rfc/rfc4862
- RFC 5227, IPv4 Address Conflict Detection: https://www.rfc-editor.org/rfc/rfc5227
- RFC 5737 and RFC 3849, documentation ranges: https://www.rfc-editor.org/rfc/rfc5737, https://www.rfc-editor.org/rfc/rfc3849
- RFC 5952, A Recommendation for IPv6 Address Text Representation: https://www.rfc-editor.org/rfc/rfc5952
- RFC 6164 (/127 links), RFC 6177 (end-site assignment): https://www.rfc-editor.org/rfc/rfc6164, https://www.rfc-editor.org/rfc/rfc6177
- RFC 6598, Shared Address Space: https://www.rfc-editor.org/rfc/rfc6598
- RFC 6890, Special-Purpose IP Address Registries: https://www.rfc-editor.org/rfc/rfc6890
- RFC 7239, Forwarded HTTP Extension: https://www.rfc-editor.org/rfc/rfc7239
- RFC 8200, IPv6 Specification: https://www.rfc-editor.org/rfc/rfc8200
- RFC 8415, DHCPv6: https://www.rfc-editor.org/rfc/rfc8415
- IANA IPv4 / IPv6 special-purpose registries: https://www.iana.org/assignments/iana-ipv4-special-registry/, https://www.iana.org/assignments/iana-ipv6-special-registry/
- Linux man pages: ip-route(8), ip-neighbour(8), ip-rule(8), IPV6_V6ONLY(2const): https://man7.org/linux/man-pages/man8/ip-route.8.html, https://man7.org/linux/man-pages/man8/ip-neighbour.8.html, https://man7.org/linux/man-pages/man8/ip-rule.8.html, https://man7.org/linux/man-pages/man2/IPV6_V6ONLY.2const.html
- AWS VPC, subnet sizing and CIDR blocks: https://docs.aws.amazon.com/vpc/latest/userguide/subnet-sizing.html, https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html
- AWS EKS best practices, IP optimisation: https://docs.aws.amazon.com/eks/latest/best-practices/ip-opt.html
- Docker networking, bridge driver, Compose networking: https://docs.docker.com/engine/network/, https://docs.docker.com/engine/network/drivers/bridge/, https://docs.docker.com/compose/how-tos/networking/
- Kubernetes cluster networking, kube-apiserver, kube-controller-manager, kubelet, kubeadm init, large clusters: https://kubernetes.io/docs/concepts/cluster-administration/networking/, https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/, https://kubernetes.io/docs/reference/command-line-tools-reference/kube-controller-manager/, https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/, https://kubernetes.io/docs/reference/setup-tools/kubeadm/kubeadm-init/, https://kubernetes.io/docs/setup/best-practices/cluster-large/
- PostgreSQL network address types and functions: https://www.postgresql.org/docs/current/datatype-net-types.html, https://www.postgresql.org/docs/current/functions-net.html
- Go
net/netipandnet(read viago doc net/netipandgo doc net.Listen, Go 1.27): https://go.dev/src/net/netip/netip.go - Laravel 13 docs: validation, requests (trusted proxies), routing (rate limiting), migrations: https://laravel.com/docs/13.x/validation, https://laravel.com/docs/13.x/requests, https://laravel.com/docs/13.x/routing, https://laravel.com/docs/13.x/migrations