# IP addressing and subnets: reading CIDR

Read any CIDR block at a glance, plan a VPC into subnets that will not collide later, and know which addresses are private, public or reserved, with IPv6 in brief.

Course: [Networking for DevOps](https://devops.rajeev.pro/courses/networking), lesson 2. About 25 minutes, beginner. Source: https://devops.rajeev.pro/courses/networking/02-ip-addressing

## What you will learn

- Read a CIDR block and work out its size and range
- Split a /16 into /24 subnets and check whether an address is inside one
- Tell private, public and reserved addresses apart
- Recognise IPv6 addresses and the ones your machine already has

> **Lab status.** **Verified lab:** every number below comes from Python's `ipaddress` module and `ip` on a Linux host. The output shown is real. <br />**Cloud lab:** none needed.

You'll write CIDR blocks for the rest of your career: VPCs, subnets, security group rules, Kubernetes Pod ranges,
Docker networks. Reading them should be instant.

## An address and a prefix

An IPv4 address is 32 bits, written as four numbers from 0 to 255. The `/number` after it says how many of those
bits, from the left, name the **network**. The rest number the **hosts** inside it.

> **Figure.** 10.0.0.0/16 drawn as four octets: 10 and 0 are the network part, the last two octets are the host part. 65,536 addresses from 10.0.0.0 to 10.0.255.255, mask 255.255.0.0. Below, common prefixes: /32 is 1 address, /28 is 16, the smallest AWS subnet, /24 is 256, /20 is 4,096, /16 is 65,536, a typical VPC.

```text
$ python3 -c "import ipaddress as i; n=i.ip_network('10.0.0.0/16'); print(n, n.num_addresses, n.netmask, n[0], n[-1])"
10.0.0.0/16 65536 255.255.0.0 10.0.0.0 10.0.255.255
```

Your machine from lesson 1, `eth0 172.29.94.205/20`, sits in the network `172.29.80.0/20`: 4,096 addresses from
`172.29.80.0` to `172.29.95.255`. Anything outside that range goes to the gateway. Note that the first address
(the network itself) and the last (broadcast) aren't usable for hosts, and AWS reserves five per subnet.

## Plan subnets

A real network is one big block split into smaller ones. The common pattern: one `/16` per VPC, one `/24` per
subnet, split by availability zone and by public or private.

> **Figure.** A VPC 10.0.0.0/16 with two zones. Zone a: public 10.0.1.0/24 for load balancers and NAT, private 10.0.11.0/24 for app servers and databases. Zone b: public 10.0.2.0/24 and private 10.0.12.0/24. Public subnets route to an internet gateway, private ones through NAT.

```text
$ python3 -c "import ipaddress as i; s=list(i.ip_network('10.0.0.0/16').subnets(new_prefix=24)); print(len(s), s[0], s[1], s[-1])"
256 10.0.0.0/24 10.0.1.0/24 10.0.255.0/24
$ python3 -c "import ipaddress as i; print(i.ip_address('10.0.3.7') in i.ip_network('10.0.0.0/22'), i.ip_address('10.0.4.7') in i.ip_network('10.0.0.0/22'))"
True False
```

A `/16` holds 256 `/24` subnets. A `/22` is four `/24`s glued together (10.0.0.0 to 10.0.3.255), so `10.0.3.7` is
inside and `10.0.4.7` isn't. You don't need to do binary in your head: `ipaddress` or cidr.xyz will check any plan.

> **Plan before you build.** CIDR ranges are painful to change later, and networks you ever want to connect (VPC peering, a VPN to the office, Kubernetes Pods reaching a database) must not overlap. Give each environment its own range, such as 10.10.0.0/16 for dev and 10.20.0.0/16 for prod.

## Private, public and reserved

Three ranges are set aside for private networks and are never routed on the internet. Everything else is public.

> **Figure.** Three private ranges: 10.0.0.0/8 with 16.7 million addresses for VPCs and offices, 172.16.0.0/12 with 1 million for Docker and WSL, 192.168.0.0/16 for home routers. A router doing NAT rewrites the private source to one public IP before the internet, which routes public addresses only. Also reserved: 127.0.0.0/8 loopback, 169.254.0.0/16 link-local, 100.64.0.0/10 carrier NAT.

```text
$ python3 -c "import ipaddress as i; [print(a, i.ip_address(a).is_private) for a in ('10.1.2.3','172.20.0.5','192.168.1.10','8.8.8.8','100.64.0.1')]"
10.1.2.3 True
172.20.0.5 True
192.168.1.10 True
8.8.8.8 False
100.64.0.1 False
```

Your laptop, your Docker containers and your VPC servers all use private addresses. When they reach the internet,
a router swaps the private source address for a public one (NAT, lesson 7). Ask `curl -4 https://ifconfig.me` and
you'll see the public address the world sees, not your `172.x` or `192.168.x` one. `169.254.169.254` is one
link-local address you'll meet often: it's where cloud servers fetch their metadata and credentials.

## IPv6 in brief

IPv4 has about 4.3 billion addresses, which ran out years ago; NAT is how the internet copes. **IPv6** uses 128
bits, written in hexadecimal groups, with `::` standing for a run of zeros. Your machine already has one:

```text
$ ip -6 addr show eth0 | grep inet6
    inet6 fe80::215:5dff:fedd:4d64/64 scope link proto kernel_ll
```

`fe80::/10` is **link-local**: every interface makes one itself, and it only works on the local link. A global
IPv6 address (starting with `2` or `3`) is routable everywhere with no NAT. AWS, Kubernetes and most CDNs support
IPv6, and AWS now charges for every public IPv4 address, which is one reason teams are adopting it. The CIDR rules
are the same: a VPC gets a `/56`, a subnet a `/64`.

## Mission: Plan a two-environment network

Pick non-overlapping /16 ranges for dev and prod. Split each into two public and two private /24 subnets across two zones, leaving gaps for growth. Prove with Python that none of your eight subnets overlap and that each sits inside its VPC.

- You need: Python 3
- You'll have: ~/subnet-plan.txt

```sh
$ python3 - <<'EOF' > ~/subnet-plan.txt
import ipaddress as i, itertools
plan = {'dev': '10.10.0.0/16', 'prod': '10.20.0.0/16'}
subnets = {f'{env}-{tier}-{z}': f'{plan[env][:-6]}{n}.0/24'
           for env in plan for (tier, base) in (('public', 1), ('private', 11)) for z, n in (('a', base), ('b', base + 1))}
for name, cidr in subnets.items():
    print(name, cidr, i.ip_network(cidr).subnet_of(i.ip_network(plan[name.split('-')[0]])))
print('overlaps:', [p for p in itertools.combinations(subnets.values(), 2) if i.ip_network(p[0]).overlaps(i.ip_network(p[1]))])
EOF
$ cat ~/subnet-plan.txt
```

Every line should end in `True`, and the overlaps list should be empty.

## Try it

- Work out how many addresses a /20 holds, then check with Python's ipaddress module.
- Split 10.0.0.0/16 into /24 subnets and name the first and last.
- Check whether 10.0.4.7 is inside 10.0.0.0/22.
- Run `ip -br addr` and decode your own address and prefix.
- Do the mini mission and keep `~/subnet-plan.txt`.

## Quiz

1. How many addresses does a /24 contain?
   - 24
   - 128
   - **256** (answer)
   - 65,536
   Why: 32 bits minus 24 fixed bits leaves 8 host bits, and 2 to the 8th is 256.

2. Which of these is a private address?
   - 8.8.8.8
   - **172.20.0.5** (answer)
   - 100.64.0.1
   - 104.20.23.154
   Why: 172.16.0.0/12 runs from 172.16.0.0 to 172.31.255.255. 100.64.0.0/10 is carrier-grade NAT space, not a private range.

3. Why must two VPCs you plan to connect use different CIDR ranges?
   - AWS charges more for overlap
   - **With overlapping ranges, a route can't tell which network an address belongs to** (answer)
   - It's only a naming convention
   - They don't need to
   Why: Routing picks a destination by address range. If 10.0.1.5 exists on both sides, there is no correct answer.

## Resources

- [Python ipaddress module](https://docs.python.org/3/library/ipaddress.html) (Python Docs)
- [Address allocation for private internets (RFC 1918)](https://www.rfc-editor.org/rfc/rfc1918) (IETF)
- [VPC CIDR blocks](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html) (AWS Docs)
- [cidr.xyz, an interactive CIDR visualiser](https://cidr.xyz/) (cidr.xyz)
