Skip to content

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 forGo to
Tables to memorise in one minuteEverything in one minute
Why addresses have a network part at allWhy it exists
RFC 791, classes, CIDR, RFC 1918, IPv6 historyWhere it comes from
32 bits, dotted quad, binary, hexIPv4 anatomy
Class A/B/C and why they diedClassful addressing
/n, masks, wildcard masksCIDR and prefix length
Network, broadcast, first, last, host count; the head trickSubnet math
Splitting a /16 for VPC, Docker, podsVLSM
10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, 100.64/10, 224/4Special ranges
0.0.0.0 vs 255.255.255.255The two extreme addresses
128 bits, ::, /64, ULA, fe80::/10, zone IDs, [::1]:8080IPv6
SLAAC, DHCPv6, dual stack, why NAT is rareSLAAC, DHCPv6, dual stack
IP to MAC on IPv4, gratuitous ARP, spoofingARP
Neighbor Discovery on IPv6NDP
Routing table, longest-prefix match, default gateway, metricRouting
The exact steps when your laptop sends a packetHow a packet leaves your laptop
127.0.0.1 vs 0.0.0.0 vs ::, the Docker bind bugBinding and listening
AWS VPC, reserved addresses, IGW, NAT gateway, GCPCloud VPC addressing
Docker pools, Compose subnets, pod/service/node CIDRsContainer and Kubernetes planning
inet/cidr, X-Forwarded-For, GeoIPIPs in databases and logs
Tools and platforms side by sidePer-tool and per-platform behaviour
Bitwise AND, ARP bytes, neighbor states, errno values, sysctlsMechanics
Go + Laravel fixes for the classic bugsSolving the classic problems
Symptom → cause → fixTroubleshooting
Which prefix size for whatChoosing
Monolith to multi-regionIn architecture
Hands-onLab
Wrong beliefs, a cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

Prefix sizes you meet every week. Every row is unpacked in Subnet math.

PrefixMaskAddressesUsable hosts (classic LAN)Where you see it
/8255.0.0.016,777,21616,777,21410.0.0.0/8, 127.0.0.0/8
/12255.240.0.01,048,5761,048,574172.16.0.0/12, kubeadm Service CIDR 10.96.0.0/12
/16255.255.0.065,53665,534AWS VPC maximum, Docker 172.17.0.0/16
/20255.255.240.04,0964,094 (AWS: 4,091)Private subnet for Kubernetes nodes
/24255.255.255.0256254 (AWS: 251)Home LAN, one Kubernetes node's pod range
/27255.255.255.2243230Small DMZ or database subnet
/28255.255.255.2401614 (AWS: 11)AWS smallest subnet
/30255.255.255.25242Old-style point-to-point link
/31255.255.255.25422 (RFC 3021)Modern point-to-point link
/32255.255.255.25511One host: a route, an allow-list entry
/64 (IPv6)n/a2^64allEvery IPv6 LAN segment

Special ranges. Every row is unpacked in Special ranges.

RangeNamePlain words
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16Private (RFC 1918)Reuse freely inside your network; never routed on the internet
100.64.0.0/10Shared Address Space / CGNAT (RFC 6598)Your ISP's NAT; also Tailscale's range
127.0.0.0/8, ::1LoopbackNever leaves the host
169.254.0.0/16, fe80::/10Link-localValid only on one link; 169.254.169.254 is the cloud metadata service
224.0.0.0/4, ff00::/8MulticastOne-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::/32Documentation (RFC 5737, RFC 3849)Use in examples and tests, never in production
0.0.0.0, ::UnspecifiedAs a bind address: all interfaces. As a route: default
255.255.255.255Limited broadcastEveryone on this link, never forwarded

Five commands.

QuestionLinuxmacOS
What are my addresses?ip -br addrifconfig
Which route will this destination use?ip route get 1.1.1.1route -n get 1.1.1.1
What is in my routing table?ip route / ip -6 routenetstat -rn
Who are my neighbors (IP → MAC)?ip neigharp -an, ndp -an
Is this address inside that subnet?ipcalc, sipcalc, Go netip.Prefix.Containssame

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 everythingLittle waste; fits tiny tiers
One broadcast/failure domain for many hostsMany subnets, many route-table entries
Easy to collide with another network's rangeEasy to run out of addresses (pods!)
Fewer firewall rulesFine-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 ​

  1. "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.
  2. "/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.
  3. "127.0.0.1 and 0.0.0.0 are both 'localhost'." As a bind address, 127.0.0.1 accepts only connections from the same network namespace; 0.0.0.0 accepts 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 bits and Destination 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 (::1 loopback, fe80::/10 link-local, IPv4-mapped ::ffff:a.b.c.d). RFC 4193 (October 2005) reserves FC00::/7 for 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.

text
 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 = 167775239

The same four bytes on the wire (from printf '\x0a\x00\x0c\x07' | xxd on the author's machine) and as sipcalc sees them:

text
00000000: 0a00 0c07                                ....

Host address (decimal)	- 167775239
Host address (hex)	- A000C07

Real 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).

NotationExampleWho accepts it
Dotted quad10.0.12.7Everyone
Integer167775239ping 167775239 (inet_aton), MySQL INET_NTOA()
Hex0x0A000C07inet_aton; Go netip.ParseAddr rejects
Leading zeros010.0.12.7Ambiguous (octal in inet_aton); Go and PHP filter reject
IPv4-mapped IPv6::ffff:10.0.12.7Dual-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:

ClassLeading bitsFirst octetImplied maskToday
A00–127/8Legacy name only
B10128–191/16Legacy name only
C110192–223/24Legacy name only
D1110224–239n/aMulticast 224.0.0.0/4
E1111240–255n/aReserved 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.

10.0.12.7/20 (32 bits, written as four decimal octets)10012700001010 00000000 00001100 0000011111111111 11111111 11110000 00000000network part: 20 bits (prefix length)host part: 32 - 20 = 12 bitsmask /20 = 255.255.240.0 (wildcard 0.0.15.255) address AND mask = networkhost bits all 0 / all 1network 10.0.0.0broadcast 10.0.15.255size of the block2^12 = 4096 addresses4096 - 2 = 4094 hosts (.0.1 to .15.254)
text
 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 valuePrefix bits in that octetBlock size in that octet
25581
25472
25264
24858
240416
224332
192264
1281128
00256

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):

text
 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>):

InputNetworkBroadcastFirst hostLast hostTotalUsable
192.168.1.0/24192.168.1.0192.168.1.255.1.254256254
192.168.1.64/27192.168.1.64192.168.1.95.65.943230
10.0.0.4/3010.0.0.410.0.0.7.5.642
10.0.0.0/3110.0.0.0none (RFC 3021).0.122
10.0.0.9/3210.0.0.9none (host).9.911
10.0.12.7/2010.0.0.010.0.15.25510.0.0.110.0.15.25440964094

Real output for the last row:

text
$ 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     4094

And ipcalc (Alpine ipcalc package) agrees:

text
$ 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:	4094

Real 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.

text
 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/16

go 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):

BlockRFCMeaningRouted on the internet?Typical sighting
0.0.0.0/8791/6890"This network"; 0.0.0.0 = unspecifiedNoBind address, default route
10.0.0.0/81918PrivateNoVPCs, corporate LANs
100.64.0.0/106598Shared Address Space (CGNAT)NoMobile ISPs, Tailscale, EKS custom networking
127.0.0.0/81122LoopbackNo (must not leave the host)localhost
169.254.0.0/163927IPv4 link-localNoDHCP failed; 169.254.169.254 cloud metadata
172.16.0.0/121918PrivateNoDocker 172.17.0.0/16 and friends
192.0.2.0/245737TEST-NET-1 documentationNoDocs and tests
192.168.0.0/161918PrivateNoHome routers, Docker pool 192.168.0.0/16
198.18.0.0/152544BenchmarkingNoNetwork test labs
198.51.100.0/245737TEST-NET-2 documentationNoDocs and tests
203.0.113.0/245737TEST-NET-3 documentationNoDocs and tests
224.0.0.0/41112MulticastScopedmDNS 224.0.0.251, VRRP 224.0.0.18
240.0.0.0/41112Reserved (former class E)NoNever assign
255.255.255.255/32919Limited broadcastNoDHCP discover
::1/1284291IPv6 loopbackNolocalhost on IPv6
::/1284291IPv6 unspecifiedNoBind [::]
::ffff:0:0/964291IPv4-mappedNoDual-stack socket peers
fc00::/74193Unique Local AddressNoDocker IPv6 pools, private IPv6
fe80::/104291IPv6 link-localNoEvery IPv6 interface, NDP
ff00::/84291IPv6 multicastScopedff02::1 all nodes
2001:db8::/323849IPv6 documentationNoDocs and tests

Real output of the Go classifier in this chapter:

text
$ 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
::                     unspecified

Real 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.

text
 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.

text
 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)     ::1
text
00000000: 2001 0db8 abcd 0012 0000 0000 0000 0001   ...............
00000000: 0000 0000 0000 0000 0000 ffff c0a8 010a   ................   <- ::ffff:192.168.1.10
PrefixMeaningWho gets it
/128One addressLoopback, a host route
/64One LAN segment (SLAAC requires it)Every subnet, every Kubernetes node (--node-cidr-mask-size-ipv6 default 64)
/56256 /64sTypical home or small site (RFC 6177)
/4865,536 /64sEnterprise site
/32ISP-sized2001:db8::/32 documentation
ScopePrefixExampleLeaves the link?
Loopback::1/128::1No
Link-localfe80::/10fe80::1496:3daa:ddc1:3c65%en0No
Unique local (ULA)fc00::/7fd00:ab:cd::2Inside your organisation only
Global unicast2000::/32001:db8:abcd:12::1Yes
Multicastff00::/8ff02::1, ff02::1:ff00:3By scope

Real addresses from a Docker container on an IPv6 network (docker network create --ipv6 --subnet fd00:ab:cd::/64 ...):

text
$ 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 medium

The 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:

MechanismRFCWhat it givesWho decides the address
SLAAC4862Prefix from Router Advertisement + self-made interface IDThe host
Stateless DHCPv68415DNS servers etc., address still from SLAACHost (address), server (options)
Stateful DHCPv68415Leased addresses, like DHCPv4The server
DHCPv6 Prefix Delegation8415A whole /56 or /48 to a routerISP's server
Dual stack-Both an IPv4 and an IPv6 address per interfaceBoth mechanisms
text
 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 address

Real 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):

text
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:

text
$ 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
PlatformSee the cacheClear it
Linuxip neigh, cat /proc/net/arpip neigh flush dev eth0
macOSarp -ansudo arp -d -a
Windowsarp -aarp -d *
AWS VPCNot visible: the VPC answers ARP itselfn/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:

text
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
JobIPv4IPv6
IP → MACARP request/reply (broadcast)NS/NA (solicited-node multicast)
Find the routerDHCP option 3Router Advertisement
Duplicate detectionRFC 5227 ARP probeDAD (NS for own address)
Announce a moveGratuitous ARPUnsolicited NA
Spoofing defenseDynamic ARP Inspection (switch)RA Guard, SEND (rarely deployed)
Toolip neigh, arp -anip -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:

text
$ 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 0

On 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:

text
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
PlatformShow tableAsk for one destinationAdd a route
Linuxip route, ip -6 route, ip ruleip route get 1.1.1.1ip route add 10.9.0.0/16 via 10.0.0.1
macOSnetstat -rnroute -n get 1.1.1.1sudo route -n add -net 10.9.0.0/16 10.0.0.1
Windowsroute printFind-NetRoute -RemoteIPAddress 1.1.1.1route add 10.9.0.0 mask 255.255.0.0 10.0.0.1
AWSVPC route tableReachability AnalyzerRoute table entry (local, igw-, nat-, pcx-, tgw-)
Kubernetes nodeip 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.

app: connect(10.0.2.9:5432)kernel picks a source IP and an egress routerouting table: longest-prefix matchmost specific /n wins; tie broken by metric0.0.0.0/0 (default) matches everything, last resortmatched route has "via"?on-link (scope link) vs next hopno: destination is on-linkARP / NDP for 10.0.2.9 itselfframe dst MAC = the destinationyes: via gateway 10.0.0.1ARP / NDP for the GATEWAY's IPIP dst unchanged, MAC dst = routerno route at allENETUNREACH"Network is unreachable"neighbor cache (ip neigh / arp -a)hit: send now; miss: broadcast who-has, queue packetno answer: "No route to host" (EHOSTUNREACH)
text
 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
ErrorerrnoMeans
Network is unreachableENETUNREACHNo route matched (no default route)
No route to hostEHOSTUNREACHRoute exists but ARP/NDP got no answer, or an ICMP host-unreachable came back
Cannot assign requested addressEADDRNOTAVAILYou tried to bind/source an IP the host does not own
Connection refusedECONNREFUSEDThe host answered, nothing listens on that address:port (see Binding)
TimeoutETIMEDOUTPackets 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):

text
$ 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:yes

The Docker bind bug, reproduced on Docker Desktop for Mac (nc listening inside the container, -p 18080:8080 vs -p 18081:8080):

text
$ 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 addressReachable from same hostFrom other containers/hostsTypical use
127.0.0.1 / ::1Yes (same namespace only)NoAdmin ports, a sidecar-only port, local dev DB
0.0.0.0YesYes (IPv4)Containers, servers behind a firewall
[::] with v6only=0YesYes (IPv4 + IPv6)Default for Go ":8080", nginx listen [::]:80 + ipv6only=off
Specific IP (10.0.1.5)Via that IPOnly via that interfaceMulti-homed hosts, keepalived VIPs
Docker -p 127.0.0.1:5432:5432Host onlyNoPublish 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.

Internet gatewayVPC 10.0.0.0/16 (65,536 addresses)public-a 10.0.0.0/24route 0.0.0.0/0 -> IGW; NAT gatewayAWS reserves .0 .1 .2 .3 and .255public-b 10.0.1.0/24route 0.0.0.0/0 -> IGW; NAT gatewayload balancer nodes live hereprivate-a 10.0.16.0/20 (nodes)route 0.0.0.0/0 -> NAT GW in public-a4,091 usable on AWSprivate-b 10.0.32.0/20 (nodes)route 0.0.0.0/0 -> NAT GW in public-bdatabases: 10.0.48.0/20, 10.0.64.0/20Kubernetes pod CIDR (cluster CIDR) 10.0.128.0/17node CIDR mask /24: node-1 10.0.128.0/24, node-2 10.0.129.0/24 ... 128 nodes maxeach node: 256 addresses for at most 110 pods (kubelet default max-pods)overlay CNIs use a range outside the VPC; VPC-native CNIs take pod IPs from the node subnetsService CIDR 172.20.0.0/16virtual ClusterIPs, never on any interfacemust not overlap pods, nodes or VPCMust stay disjoint fromoffice VPN 192.168.0.0/16, peered VPC 10.1.0.0/16Docker 172.17.0.0/16 on CI runners
text
 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
ItemAWSGCPKubernetes on either
Network scopeVPC per region, subnet per AZVPC global, subnet per regionCluster inside the VPC
Size limitsVPC and subnet /16 to /28Primary ranges sized freely within limits (check docs)Pod/Service CIDRs set at creation
Reserved per subnet5 (.0 .1 .2 .3 + last)Several (check docs)Service CIDR first IP = kubernetes Service
Internet egressIGW (public) or NAT gateway (private)Cloud NATNode or NAT gateway
Private service accessVPC endpointsPrivate Google Accessn/a
Joining VPCsPeering, Transit Gateway (no overlapping CIDRs)VPC Peering, Shared VPCSame 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/14 in /16 pieces and 192.168.0.0/16 in /20 pieces. The default bridge is 172.17.0.0/16 with gateway 172.17.0.1. Compose creates <project-name>_default per 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-cidr default is 10.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-pods default is 110, and the scalability guide says "No more than 110 pods per node".
text
 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
ProductDefault rangeWhere you change it
Docker default bridge172.17.0.0/16daemon.json bip
Docker user networks / ComposePools from 172.17.0.0/16 ... 192.168.0.0/16default-address-pools, networks.ipam.config in Compose
Docker IPv6ULA prefix when no pool givendefault-address-pools with an IPv6 base
kubeadm Service CIDR10.96.0.0/12--service-cidr
kubeadm pod CIDRnone (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 CNIPods take VPC subnet IPsSecondary 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:

sql
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.

DatabaseNative typeContainment queryIndex
PostgreSQLinet, cidr, macaddrnet >>= ipGiST/SP-GiST inet_ops, B-tree for equality
MySQL 8none: VARBINARY(16) + INET6_ATON()ip BETWEEN start AND endB-tree on start/end
SQLitenone: text or blobapplication sideB-tree on blob
ClickHouseIPv4, IPv6isIPAddressInRange()primary key / skip index
Redisnonesorted 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 ​

ToolPlatformWhat it answersExample
ip addr / ip -br addrLinux (iproute2)Addresses per interfaceip -4 addr show eth0
ifconfigmacOS, BSD, old LinuxSameifconfig en0
ip route, ip -6 routeLinuxRouting tableip route show table all
ip route getLinuxRoute + source for one destinationip route get 1.1.1.1
ip ruleLinuxPolicy routing rulesip rule show
netstat -rn, route -n getmacOSTable, single lookuproute -n get default
ip neighLinuxARP/NDP cache with statesip -s neigh
arp -a / arp -anmacOS, Windows, Linux (net-tools)ARP cachearp -an
ndp -anmacOSIPv6 neighbor cachendp -an
ping, ping6 / ping -6allReachability (ICMP)ping6 ::1
traceroute, traceroute6, mtr, tracertallHops (TTL expiry)traceroute -n 1.1.1.1
ipcalcLinux packages (Alpine/Debian differ)Subnet mathipcalc 10.0.12.7/20
sipcalcLinux, HomebrewSubnet math incl. IPv6 expansionsipcalc 2001:db8::/64
tcpdump -eallFrames incl. MAC, ARP, NDPtcpdump -nn -e arp
Go net/netipGo 1.18+Parse, contains, overlapsnetip.MustParsePrefix(...).Contains(a)
PHP filter_var / inet_ptonPHPValidate, packfilter_var($ip, FILTER_VALIDATE_IP)

Real sipcalc IPv6 output:

text
$ 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 / frameworkParseContainsNotes
Go net/netipParseAddr, ParsePrefixPrefix.Contains, Prefix.OverlapsValue types, comparable, map keys; Unmap() for ::ffff:
Go net (old)net.ParseIP, net.ParseCIDRIPNet.ContainsSlices, not comparable; prefer netip
PHPinet_pton, filter_varByte masks (see SubnetMath)FILTER_FLAG_NO_PRIV_RANGE, NO_RES_RANGE, GLOBAL_RANGE
Laravel 13ip, ipv4, ipv6, Rule::ip()->version(6)Symfony IpUtils::checkIp() (used by TrustProxies)$request->ip() respects trusted proxies
Pythonipaddress.ip_networkaddr in net, net.overlaps()strict=False to allow host bits
PostgreSQLinet, cidr>>=, &&GiST inet_ops

Mechanics ​

Bitwise rules ​

text
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)FieldValue
ffff ffff ffffEthernet destinationBroadcast
3656 d7eb 9586Ethernet sourceAsking container
0806EtherTypeARP
0001Hardware type (ar$hrd)Ethernet (1)
0800Protocol type (ar$pro)IPv4
06 / 04Hardware / protocol address length6 / 4 bytes
0001Opcode1 = request (2 = reply)
3656 d7eb 9586Sender MAC36:56:d7:eb:95:86
0afa 0004Sender IP10.250.0.4
0000 0000 0000Target MACUnknown yet
0afa 0003Target IP10.250.0.3

Neighbor states (Linux) ​

StateMeaning (ip-neighbour(8))What you do
INCOMPLETEResolution in progressWait; persistent = host down or wrong subnet
REACHABLEConfirmed recentlyFine
STALEValid but suspicious; will be re-checked on useNormal for idle peers
DELAY / PROBERe-confirmation in progressTransient
FAILEDNo answerWrong IP, host down, VLAN/security group mismatch
PERMANENT / NOARPStatic entry / no resolution neededSet by admin or interface type

Knobs ​

KnobDefaultEffect
net.ipv4.ip_forward0 (Docker/Kubernetes set 1)Host routes packets between interfaces
net.ipv6.bindv6only0:: sockets also accept IPv4-mapped peers
net.ipv4.conf.*.arp_ignore / arp_announce0Which ARP requests to answer; needed for LVS/VIP setups
net.ipv4.neigh.default.gc_thresh1/2/3128/512/1024Neighbor table size; raise on large flat networks and big Kubernetes nodes
net.ipv6.conf.*.accept_ra1Accept Router Advertisements
net.ipv6.conf.*.use_tempaddrdistro-dependentPrivacy (temporary) addresses
Docker bip, default-address-pools172.17.0.1/16, built-in poolsContainer ranges
kube --cluster-cidr, --service-cluster-ip-range, --node-cidr-mask-sizenone, none (kubeadm 10.96.0.0/12), 24/64Cluster 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 ​

ProblemSolutionHowAdvantageCost / limitation
Subnet math by handCalculator in codenetip / SubnetMathNo off-by-oneNone
Overlapping CIDRsOverlap check in CIPrefix.Overlaps, PostgreSQL &&Catches peering/VPN conflicts before deployNeeds one source of truth
App unreachable in DockerBind 0.0.0.0/[::] from configADDR=:8080Works in every runtimeExpose only via published ports/firewall
Wrong client IPTrusted-proxy walkRight-to-left over XFF, stop at first untrustedSpoof-proofMust list LB subnets, both families
Querying "is IP in a blocked net?"cidr + GiSTnetwork >>= ipIndex scanPostgreSQL only; MySQL needs ranges
IPv6 rate-limit bypassKey by /64 (and /24)RateKeyOne customer = one bucketCGNAT shares IPv4 /24s; keep limits generous
SSRF to metadata/private rangesReject non-global targetsFILTER_FLAG_GLOBAL_RANGE, classifierBlocks 169.254.169.254Resolve DNS first and check the resolved IP
Pod IP exhaustionSize cluster CIDR from max nodes/n = node_mask - log2(nodes)Predictable growthHard to change later

Subnet calculator (Go and PHP) ​

go
// 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
<?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:

text
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/24

Overlapping CIDRs ​

text
$ 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 1

Run 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 ​

go
// 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 ​

go
// 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")))
}
text
$ 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::/64

Laravel 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
<?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
<?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):

text
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=no

Note that NO_PRIV_RANGE alone lets 127.0.0.1, 169.254.169.254 and CGNAT through; use GLOBAL_RANGE.

Storing IPs ​

php
<?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
<?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
<?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 ​

go
// 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)
	}
}
text
$ 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 ​

SymptomLikely causeCheckFix
curl: (56) Connection reset / Connection refused to a published portApp bound to 127.0.0.1 in the containerdocker exec c netstat -tlnBind 0.0.0.0 / [::]
Container cannot reach a 192.168.x/172.x host on the VPNDocker network overlaps the VPN rangeip route get <ip> on the hostdefault-address-pools, recreate networks
Network is unreachableNo matching route (no default gateway)ip routeAdd default route / fix DHCP
No route to hostARP/NDP failed or ICMP unreachableip neigh shows FAILEDCorrect subnet/VLAN, security group
Address is 169.254.x.xDHCP failed, link-local fallbackip addr, DHCP logsFix DHCP reachability
VPC peering request rejectedOverlapping CIDRsOverlap checkerRe-address one side, or use PrivateLink/NAT
Pods stuck ContainerCreating, "no IP addresses available"Node pod CIDR or VPC subnet exhaustedkubectl describe node, CNI logsBigger cluster CIDR, prefix delegation, secondary CIDR
All requests appear from 10.0.x.xProxy not trustedLog REMOTE_ADDR and XFFtrustProxies(at: [...])
Rate limit bypassed with fake XFFTrusting * on a directly reachable appSend XFF with curlTrust only LB CIDRs, firewall direct access
IPv6 works then stops on the LANICMPv6 blocked, NDP brokenip -6 neighAllow ICMPv6 133–137
Clients talk to the old server after failoverStale ARP cachesarp -an on clientsSend gratuitous ARP (keepalived does)
cidr insert fails: "bits set to right of mask"Host bits in a network valueMasked formInsert network(x) or use inet
Go net.Dial fails with "too many colons in address"IPv6 without bracketsPrint the addressnet.JoinHostPort
neighbor table overflow! in dmesgNeighbor cache too smallcount ip neigh linesRaise gc_thresh*

Choosing ​

SituationChooseExtra techniqueReason
New AWS VPC per environment/16 from a company plan (10.10/16, 10.20/16...)Overlap check in CIPeering and Transit Gateway need disjoint ranges
Public subnet (LB, NAT GW)/24 per AZFew hosts, IGW routeSmall, rarely grows
Private node subnet with VPC-native CNI/19–/20 per AZPrefix delegationEvery pod consumes a VPC IP
Kubernetes pod CIDR (overlay CNI)/16 for up to 256 nodes at /24 eachOutside the VPC and VPN ranges110 pods per node fit in /24
Kubernetes Service CIDR/16 or kubeadm /12Disjoint from everythingVirtual, but routed by kube-proxy
Docker hosts and laptopsPools in a reserved 10.200.0.0/16, size /24daemon.jsonAvoid hotel/VPN 172.x/192.168.x
Point-to-point link/31 (IPv4), /127 (IPv6, RFC 6164)n/aNo waste
One host in an allow-list or route/32, /128n/aExact match
IPv6 LANAlways /64SLAACRequired by SLAAC, privacy addresses
IPv6 site/56 or /48Plan by nibble boundaries256 or 65,536 subnets
Storing client IPsPostgreSQL inet; MySQL VARBINARY(16)GiST inet_opsContainment 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.

text
 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 column

Distributed 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 ​

LoadAddressing 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-regionRegion-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).

  1. 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:

    bash
    cd 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/24
  2. Inspect 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. Compare ping -c1 127.0.0.2 on macOS (no reply: only 127.0.0.1 is configured on lo0) and in a Linux container (reply: Linux routes the whole 127.0.0.0/8 to lo, see ip route show table local).

  3. Two containers and ARP.

    bash
    docker 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 ... REACHABLE
  4. IPv6 and NDP. docker network create --ipv6 --subnet fd00:ab:cd::/64 ipnet6-lab, start two containers, capture tcpdump -nn -e 'icmp6 and (ip6[40]==135 or ip6[40]==136)' while ping -6 the other. Expect a neighbor solicitation to ff02::1:ff00:3 (MAC 33:33:ff:00:00:03) and an advertisement back. Check the EUI-64 link-local address against the MAC.

  5. The 127.0.0.1 bind bug.

    bash
    docker 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 -tln

    Then run go run ./listen to see the same matrix for 127.0.0.1, ::1, 0.0.0.0, [::] and tcp6.

  6. IPs in PostgreSQL. docker run -d --rm --name ippg -e POSTGRES_PASSWORD=x postgres:18-alpine, then run the SQL session: try inserting 10.0.12.7/20 into a cidr column, build the GiST index, and confirm EXPLAIN shows an index scan for network >>= '10.7.12.99'.

Clean up: docker rm -f ipa ipb ipc bindbad bindgood ippg; docker network rm ipnet-lab ipnet6-lab.

Common misconceptions ​

BeliefReality
A /24 has 256 usable hosts254 on a LAN, 251 on AWS, 256 only as a pod range where the CNI decides
172.x.x.x is privateOnly 172.16.0.0/12 (172.16–172.31)
100.64.x.x is a public clientCGNAT shared space; many users behind one address
Dots mark the network boundaryThe prefix length does; /20 splits an octet
The first matching route winsThe longest prefix wins, then the metric
ARP finds the remote server's MACOnly on-link; otherwise the gateway's MAC
127.0.0.1 works inside Docker like on my laptopIt is the container's own loopback; bind 0.0.0.0
0.0.0.0 is a destinationIt is "unspecified": a bind wildcard or the default route
IPv6 needs NAT for securityThe firewall gives security; IPv6 rarely uses NAT
Blocking all ICMPv6 hardens IPv6It breaks NDP and PMTUD
The leftmost X-Forwarded-For value is the clientIt is client-controlled; walk from the right over trusted proxies
Container ranges cannot collide with anythingThey install host routes and shadow VPN/LAN ranges
/31 is uselessRFC 3021: two usable addresses on point-to-point links
A per-IP rate limit works for IPv6One host can rotate through 2^64 addresses; key by /64

Cheat sheet ​

TopicRemember
Block size256 − mask octet; network = largest multiple ≤ address
Usable IPv4 hosts2^(32−n) − 2; /31 = 2, /32 = 1; AWS −5
Private ranges10/8, 172.16/12, 192.168/16; CGNAT 100.64/10
Loopback / link-local127/8, ::1; 169.254/16, fe80::/10
ULAfc00::/7, use fd00::/8 with a random 40-bit global ID
Documentation192.0.2/24, 198.51.100/24, 203.0.113/24, 2001:db8::/32
IPv6 textlowercase, :: once and as long as possible, [addr]:port
IPv6 sizes/64 LAN, /56 home, /48 site
RoutingLongest prefix, then metric; ip route get / route -n get
On-link vs viaOn-link: ARP the destination; via: ARP the gateway
ARP/NDPip neigh, arp -an, ndp -an; gratuitous ARP on failover
BindContainers: 0.0.0.0 or [::]; host-only: 127.0.0.1
KubernetesPod, Service, node ranges all disjoint; /24 per node, 110 pods
Docker172.17.0.0/16 default; set default-address-pools to avoid VPNs
StoragePostgreSQL inet/cidr + GiST inet_ops; Laravel ipAddress()
Client IPtrustProxies(at: [LB CIDRs]), never * on a reachable app

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
IPv432-bit Internet Protocol address (RFC 791)
IPv6128-bit Internet Protocol address (RFC 8200, RFC 4291)
Octet8 bits; one of the four numbers in a dotted quad
Dotted quadDecimal text form of IPv4, 10.0.12.7
Classful addressingPre-1993 Class A/B/C/D/E split by leading bits
CIDRClassless Inter-Domain Routing; address/prefix-length notation (RFC 4632)
Prefix lengthNumber of leading network bits, the /n
Subnet maskPrefix length written as a 32-bit mask, 255.255.240.0
Wildcard maskInverted mask, 0.0.15.255; Cisco ACLs
Network addressFirst address of a block, all host bits 0
Broadcast addressLast IPv4 address of a block, all host bits 1
Limited broadcast255.255.255.255, this link only
Host routeA /32 or /128 route to a single address
VLSMVariable Length Subnet Masking: subnets of different sizes from one block
RFC 1918The three private IPv4 blocks
CGNAT / Shared Address Space100.64.0.0/10, carrier-grade NAT (RFC 6598)
Loopback127.0.0.0/8 and ::1, never leave the host
Link-local169.254.0.0/16 and fe80::/10, valid on one link only
MulticastOne-to-many addresses, 224.0.0.0/4, ff00::/8
AnycastOne address announced from many places; nearest one answers
Unspecified address0.0.0.0 / ::; bind wildcard or default route
ULAUnique Local Address, fc00::/7 (RFC 4193)
Global unicastInternet-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 IDLow 64 bits of an IPv6 address
EUI-64Interface ID built from the MAC with ff:fe inserted
Privacy extensionsRandom temporary IPv6 addresses (RFC 4941)
SLAACStateless Address Autoconfiguration (RFC 4862)
DHCPv6Stateful/stateless IPv6 configuration and prefix delegation (RFC 8415)
Dual stackIPv4 and IPv6 on the same interface/service
ARPAddress Resolution Protocol, IPv4 → MAC (RFC 826)
ARP cache / neighbor tableKernel table of IP → MAC with states
Gratuitous ARPUnsolicited ARP announcing one's own mapping
ARP spoofingForged ARP replies to intercept traffic
NDPNeighbor Discovery Protocol for IPv6 (RFC 4861)
Solicited-node multicastff02::1:ffXX:XXXX group used by NS
Router AdvertisementICMPv6 134; announces prefixes and the default router
DADDuplicate Address Detection
Routing tableList of prefixes with next hop, device and metric
Longest-prefix matchThe most specific matching route wins
Default gatewayNext hop of 0.0.0.0/0 / ::/0
On-linkDestination reachable directly on an attached link
MetricRoute preference; lower wins among equal prefixes
Policy routingChoosing a routing table by source, mark or interface (ip rule)
VPCVirtual Private Cloud, your private address block in a cloud
Internet Gateway (IGW)AWS gateway that makes a subnet public
NAT gatewayManaged NAT for private subnets' outbound traffic
Pod CIDR / cluster CIDRRange from which pod IPs are allocated
Node CIDROne node's slice of the cluster CIDR
Service CIDRRange for Kubernetes ClusterIPs
IP exhaustionNo free addresses left in a subnet or pod range
inet / cidrPostgreSQL types for host addresses and networks
X-Forwarded-ForDe facto header listing the client and proxies
Trusted proxyA proxy whose forwarding headers you believe
GeoIPMapping IP prefixes to locations/ASNs
net/netipGo package with value-type Addr and Prefix
ipcalc / sipcalcCommand-line subnet calculators
ENETUNREACH / EHOSTUNREACH"Network is unreachable" / "No route to host"

References ​

Built by Morteza Negahi