CloudAcademia
EN

Networking · Module 06 · Subnetting: Dividing and Planning IPv4 Networks

Lab: Designing and Validating an Addressing Plan

Lab60 minIntermediateMarkdown

Showing raw Markdown: the renderer could not load.

## Goal
You design the IPv4 addressing plan for a fictitious company with three sites, using VLSM inside the private block `10.20.0.0/16`. Then you check it with a small Python script that catches overlaps, undersized subnets and misaligned prefixes, and you fix a broken plan.

## Objectives
- Size each network segment with the smallest prefix that meets its host count.
- Allocate a VLSM plan per site, largest subnet first, on aligned boundaries.
- Choose one block per site so that each site can be advertised as a single summary route.
- Validate a plan automatically (containment, overlaps, capacity, spare space) and fix the faults it finds.
- (Optional) Observe on Linux how a wrong subnet mask breaks reachability.

## Prerequisites
- Python 3.8 or later (only the standard library is used). Check with `python3 --version`; on Windows use `py` instead of `python3`.
- A text editor and a terminal.
- The [lesson](lesson.md) of this module, especially VLSM and summarization.
- Optional Step 8 only: a Linux machine or VM where you can use `sudo`, with iproute2 (`ip`) and `ping` installed.

> [!WARNING]
> Steps 1–7 only create files in a folder in your home directory. Step 8 creates network namespaces and needs `sudo`: run it on a test machine or VM, not on a production server. It uses the documentation range `198.51.100.0/24` (RFC 5737) and doesn't touch your real network interfaces. Always run the [Cleanup](#cleanup) section at the end.

## Architecture
Example Corp has a head office (HQ) and two branches (BR1, BR2), connected by point-to-point WAN links. It owns the RFC 1918 block `10.20.0.0/16` for all its internal addressing.

<figure class="diagram" style="--dg-w: 900px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 900 468" width="900" height="468" role="img" aria-labelledby="subnetting-lab-sites-title subnetting-lab-sites-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="subnetting-lab-sites-title">Lab scenario: Example Corp sites and WAN links</title>
<desc id="subnetting-lab-sites-desc">Example Corp uses 10.20.0.0/16. The head office HQ has Staff, Voice, Guest, Servers and Management segments. Branch BR1 has Staff, Voice, Guest and Management. Branch BR2 has Staff, Voice and Management. Point-to-point WAN links with /31 prefixes join HQ to BR1, HQ to BR2, and BR1 to BR2 as a backup.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="899" height="467" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<text x="28" y="44" font-size="15" class="dg-text" fill="#17171c" font-weight="700" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">Example Corp · 10.20.0.0/16</text>
<g class="dg-l1"><path class="dg-stroke" d="M340 224L170 284" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M560 224L730 284" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M300 364.0H600" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/></g>
<rect class="dg-card" x="320" y="64" width="260" height="160" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(336 80) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/><path d="M10 18h4"/></g>
<text x="378" y="101" font-size="15" class="dg-text" fill="#17171c" font-weight="700">HQ</text>
<text x="338" y="132" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">Head office</text>
<g class="dg-l7"><rect class="dg-solid" x="338" y="148" width="60" height="26" rx="13" fill="#6d28d9"/><text x="368" y="165.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Staff</text></g>
<g class="dg-l5"><rect class="dg-solid" x="404" y="148" width="60" height="26" rx="13" fill="#be185d"/><text x="434" y="165.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Voice</text></g>
<g class="dg-l4"><rect class="dg-solid" x="470" y="148" width="60" height="26" rx="13" fill="#c2410c"/><text x="500" y="165.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Guest</text></g>
<g class="dg-l3"><rect class="dg-solid" x="338" y="180" width="74" height="26" rx="13" fill="#b45309"/><text x="375" y="197.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Servers</text></g>
<g class="dg-l1"><rect class="dg-solid" x="418" y="180" width="96" height="26" rx="13" fill="#0369a1"/><text x="466" y="197.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Management</text></g>
<rect class="dg-card" x="40" y="284" width="260" height="160" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(56 300) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/><path d="M10 18h4"/></g>
<text x="98" y="321" font-size="15" class="dg-text" fill="#17171c" font-weight="700">BR1</text>
<text x="58" y="352" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">Branch office</text>
<g class="dg-l7"><rect class="dg-solid" x="58" y="368" width="60" height="26" rx="13" fill="#6d28d9"/><text x="88" y="385.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Staff</text></g>
<g class="dg-l5"><rect class="dg-solid" x="124" y="368" width="60" height="26" rx="13" fill="#be185d"/><text x="154" y="385.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Voice</text></g>
<g class="dg-l4"><rect class="dg-solid" x="190" y="368" width="60" height="26" rx="13" fill="#c2410c"/><text x="220" y="385.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Guest</text></g>
<g class="dg-l1"><rect class="dg-solid" x="58" y="400" width="96" height="26" rx="13" fill="#0369a1"/><text x="106" y="417.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Management</text></g>
<rect class="dg-card" x="600" y="284" width="260" height="160" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(616 300) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/><path d="M10 18h4"/></g>
<text x="658" y="321" font-size="15" class="dg-text" fill="#17171c" font-weight="700">BR2</text>
<text x="618" y="352" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">Branch office</text>
<g class="dg-l7"><rect class="dg-solid" x="618" y="368" width="60" height="26" rx="13" fill="#6d28d9"/><text x="648" y="385.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Staff</text></g>
<g class="dg-l5"><rect class="dg-solid" x="684" y="368" width="60" height="26" rx="13" fill="#be185d"/><text x="714" y="385.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Voice</text></g>
<g class="dg-l1"><rect class="dg-solid" x="618" y="400" width="96" height="26" rx="13" fill="#0369a1"/><text x="666" y="417.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">Management</text></g>
<g class="dg-l1"><rect class="dg-bg-plain" x="177.24" y="226" width="125.52" height="24" rx="12" fill="#ffffff"/><text x="240" y="242.5" font-size="12" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle">WAN HQ–BR1 · /31</text></g>
<g class="dg-l1"><rect class="dg-bg-plain" x="597.24" y="226" width="125.52" height="24" rx="12" fill="#ffffff"/><text x="660" y="242.5" font-size="12" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle">WAN HQ–BR2 · /31</text></g>
<g class="dg-l1"><rect class="dg-bg-plain" x="353.64" y="352" width="192.72" height="24" rx="12" fill="#ffffff"/><text x="450" y="368.5" font-size="12" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle">WAN BR1–BR2 · /31 · backup</text></g>
</svg></figure>

*Figure 1. Example Corp's sites and the segments each one needs. The three WAN links are point-to-point /31 networks.*

The requirements, in hosts needed today including growth:

| Site | Segment | Hosts |
|---|---|---|
| HQ | Staff | 900 |
| HQ | Voice | 400 |
| HQ | Guest | 250 |
| HQ | Servers | 200 |
| HQ | Management | 40 |
| BR1 | Staff | 120 |
| BR1 | Voice | 60 |
| BR1 | Guest | 50 |
| BR1 | Management | 10 |
| BR2 | Staff | 55 |
| BR2 | Voice | 25 |
| BR2 | Management | 6 |
| WAN | HQ-BR1, HQ-BR2, BR1-BR2 | 2 each |

Design rules:
1. Each site gets **one aligned block**, so that the rest of the network can reach it with one summary route.
2. All WAN links come from one infrastructure block, `10.20.255.0/24`, and use /31 prefixes (RFC 3021).
3. Inside each site, allocate segments largest first, starting at the beginning of the site block.

## Steps

### Step 1 — Create a workspace
Keep every file of this lab in one folder, so cleanup is a single command.

```bash
mkdir -p ~/subnet-lab
cd ~/subnet-lab
python3 --version
```

Expected output (any version from 3.8 up works):
```text
Python 3.14.7
```

### Step 2 — Size every segment
Before you touch any addresses, decide the prefix length of each segment. Use the powers-of-two table from the lesson: find the smallest prefix whose usable hosts (2<sup>host bits</sup> − 2) cover the need.

Fill in this table on paper or in a text file:

| Site | Segment | Hosts | Prefix | Block size |
|---|---|---|---|---|
| HQ | Staff | 900 | ? | ? |
| HQ | Voice | 400 | ? | ? |
| … | … | … | … | … |

<details>
<summary>Show the sizes</summary>

| Site | Segment | Hosts | Prefix | Usable | Block size |
|---|---|---|---|---|---|
| HQ | Staff | 900 | /22 | 1022 | 1024 |
| HQ | Voice | 400 | /23 | 510 | 512 |
| HQ | Guest | 250 | /24 | 254 | 256 |
| HQ | Servers | 200 | /24 | 254 | 256 |
| HQ | Management | 40 | /26 | 62 | 64 |
| BR1 | Staff | 120 | /25 | 126 | 128 |
| BR1 | Voice | 60 | /26 | 62 | 64 |
| BR1 | Guest | 50 | /26 | 62 | 64 |
| BR1 | Management | 10 | /28 | 14 | 16 |
| BR2 | Staff | 55 | /26 | 62 | 64 |
| BR2 | Voice | 25 | /27 | 30 | 32 |
| BR2 | Management | 6 | /29 | 6 | 8 |
| WAN | each link | 2 | /31 | 2 | 2 |

</details>

### Step 3 — Choose one block per site
Add up the block sizes of each site and round up to the next power of two. That's the smallest block that holds the whole site and can still be summarized as one route.

- HQ: 1024 + 512 + 256 + 256 + 64 = 2112 addresses. The next power of two is 4096, a **/20**.
- BR1: 128 + 64 + 64 + 16 = 272 addresses. The next power of two is 512, a **/23**.
- BR2: 64 + 32 + 8 = 104 addresses. The minimum is a /25 (128). This design rounds it up to a **/24** to leave room for growth.

Place the site blocks largest first too, each on its own boundary. One valid choice:

| Site | Block | Why it's valid |
|---|---|---|
| HQ | `10.20.0.0/20` | Starts at 0, a multiple of 16 in the third octet. |
| BR1 | `10.20.16.0/23` | 16 is a multiple of 2. |
| BR2 | `10.20.18.0/24` | Follows BR1 directly. |
| WAN | `10.20.255.0/24` | Given by the design rules; far from the sites so they can grow. |

> [!TIP]
> If you want different site blocks, that's fine, as long as each one is aligned and they don't overlap. Your output in Step 6 will then differ from the one shown, but it must still end in `PASS`.

### Step 4 — Allocate the segments and write the plan
Now place the segments inside each site block, largest first. For HQ, Staff (/22) starts at `10.20.0.0`, so it ends at `10.20.3.255`. Voice (/23) starts at the next address, `10.20.4.0`, and so on.

Write the plan as a comma-separated values (CSV) file named `plan.csv`, with one row per segment and one `BLOCK` row per site:

```text
site,segment,prefix,hosts
HQ,BLOCK,10.20.0.0/20,
HQ,Staff,10.20.0.0/22,900
...
```

The columns are:
- `site`: the site name (`HQ`, `BR1`, `BR2` or `WAN`).
- `segment`: the segment name, or `BLOCK` for the site's summary block.
- `prefix`: the network in CIDR notation.
- `hosts`: hosts needed (leave it empty on `BLOCK` rows).

Try it yourself first, then compare with the reference plan.

<details>
<summary>Show the reference plan</summary>

```bash
cat > plan.csv <<'EOF'
site,segment,prefix,hosts
HQ,BLOCK,10.20.0.0/20,
HQ,Staff,10.20.0.0/22,900
HQ,Voice,10.20.4.0/23,400
HQ,Guest,10.20.6.0/24,250
HQ,Servers,10.20.7.0/24,200
HQ,Management,10.20.8.0/26,40
BR1,BLOCK,10.20.16.0/23,
BR1,Staff,10.20.16.0/25,120
BR1,Voice,10.20.16.128/26,60
BR1,Guest,10.20.16.192/26,50
BR1,Management,10.20.17.0/28,10
BR2,BLOCK,10.20.18.0/24,
BR2,Staff,10.20.18.0/26,55
BR2,Voice,10.20.18.64/27,25
BR2,Management,10.20.18.96/29,6
WAN,BLOCK,10.20.255.0/24,
WAN,HQ-BR1,10.20.255.0/31,2
WAN,HQ-BR2,10.20.255.2/31,2
WAN,BR1-BR2,10.20.255.4/31,2
EOF
```

</details>

### Step 5 — Create the validator
Checking a plan by hand is slow and error-prone. This script uses Python's standard `ipaddress` module to check every rule from the lesson:

- each prefix is a real network address (no host bits set, so it's aligned),
- everything is inside `10.20.0.0/16`, and each segment is inside its site block,
- site blocks don't overlap, and segments don't overlap,
- each segment has enough usable addresses (/31 = 2, /32 = 1, otherwise block size − 2).

It also prints the plan as a table with the mask, host range and spare addresses of each segment.

```bash
cat > validate_plan.py <<'EOF'
#!/usr/bin/env python3
"""Validate an IPv4 addressing plan stored in a CSV file (site,segment,prefix,hosts)."""
import csv
import ipaddress
import sys

TOP_BLOCK = ipaddress.ip_network("10.20.0.0/16")


def usable(net):
    """Usable host addresses: /32 = 1, /31 = 2 (RFC 3021), otherwise all minus network and broadcast."""
    if net.prefixlen == 32:
        return 1
    if net.prefixlen == 31:
        return 2
    return net.num_addresses - 2


def host_range(net):
    if net.prefixlen >= 31:
        return f"{net[0]} - {net[-1]}"
    return f"{net[1]} - {net[-2]}"


def main(path):
    errors = []
    sites, segments = {}, []
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            site, name, prefix = row["site"].strip(), row["segment"].strip(), row["prefix"].strip()
            try:
                net = ipaddress.ip_network(prefix)  # strict: host bits must be zero
            except ValueError:
                fixed = ipaddress.ip_network(prefix, strict=False)
                errors.append(f"{site}/{name}: {prefix} is not a network address (did you mean {fixed}?)")
                continue
            if not net.subnet_of(TOP_BLOCK):
                errors.append(f"{site}/{name}: {net} is outside {TOP_BLOCK}")
            if name == "BLOCK":
                sites[site] = net
            else:
                segments.append((site, name, net, int(row["hosts"])))

    # Site blocks must not overlap each other.
    names = sorted(sites)
    for i, a in enumerate(names):
        for b in names[i + 1:]:
            if sites[a].overlaps(sites[b]):
                errors.append(f"site blocks overlap: {a} {sites[a]} and {b} {sites[b]}")

    print(f"{'Site':<6} {'Segment':<12} {'Prefix':<17} {'Mask':<16} {'Host range':<29} {'Usable':>6} {'Need':>5} {'Spare':>6}")
    total_need = total_alloc = 0
    for site, name, net, need in sorted(segments, key=lambda s: s[2]):
        spare = usable(net) - need
        total_need += need
        total_alloc += net.num_addresses
        print(f"{site:<6} {name:<12} {str(net):<17} {str(net.netmask):<16} {host_range(net):<29} {usable(net):>6} {need:>5} {spare:>6}")
        if spare < 0:
            errors.append(f"{site}/{name}: {net} has {usable(net)} usable addresses but needs {need}")
        if site not in sites:
            errors.append(f"{site}/{name}: site {site} has no BLOCK row")
        elif not net.subnet_of(sites[site]):
            errors.append(f"{site}/{name}: {net} is outside its site block {sites[site]}")

    # No two segments may overlap.
    for i, (s1, n1, a, _) in enumerate(segments):
        for s2, n2, b, _ in segments[i + 1:]:
            if a.overlaps(b):
                errors.append(f"overlap: {s1}/{n1} {a} and {s2}/{n2} {b}")

    print()
    print(f"Addresses allocated to segments: {total_alloc} of {TOP_BLOCK.num_addresses} in {TOP_BLOCK}")
    print(f"Hosts required: {total_need}; spare addresses inside segments: {total_alloc - total_need}")
    print("Summary routes (one per site):", ", ".join(f"{s} {sites[s]}" for s in names))
    print()
    if errors:
        print(f"FAIL: {len(errors)} problem(s)")
        for err in errors:
            print("  -", err)
        return 1
    print("PASS: no overlaps, every segment fits its site block and its host count")
    return 0


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: python3 validate_plan.py <plan.csv>")
    sys.exit(main(sys.argv[1]))
EOF
```

> [!NOTE]
> "Spare addresses inside segments" counts every address in the allocated subnets that isn't a required host, including network and broadcast addresses. It measures how much room for growth (or waste) the plan has, not how many hosts you can still add.

### Step 6 — Validate your plan
Run the validator on your plan:

```bash
python3 validate_plan.py plan.csv
```

Expected output for the reference plan:
```text
Site   Segment      Prefix            Mask             Host range                    Usable  Need  Spare
HQ     Staff        10.20.0.0/22      255.255.252.0    10.20.0.1 - 10.20.3.254         1022   900    122
HQ     Voice        10.20.4.0/23      255.255.254.0    10.20.4.1 - 10.20.5.254          510   400    110
HQ     Guest        10.20.6.0/24      255.255.255.0    10.20.6.1 - 10.20.6.254          254   250      4
HQ     Servers      10.20.7.0/24      255.255.255.0    10.20.7.1 - 10.20.7.254          254   200     54
HQ     Management   10.20.8.0/26      255.255.255.192  10.20.8.1 - 10.20.8.62            62    40     22
BR1    Staff        10.20.16.0/25     255.255.255.128  10.20.16.1 - 10.20.16.126        126   120      6
BR1    Voice        10.20.16.128/26   255.255.255.192  10.20.16.129 - 10.20.16.190       62    60      2
BR1    Guest        10.20.16.192/26   255.255.255.192  10.20.16.193 - 10.20.16.254       62    50     12
BR1    Management   10.20.17.0/28     255.255.255.240  10.20.17.1 - 10.20.17.14          14    10      4
BR2    Staff        10.20.18.0/26     255.255.255.192  10.20.18.1 - 10.20.18.62          62    55      7
BR2    Voice        10.20.18.64/27    255.255.255.224  10.20.18.65 - 10.20.18.94         30    25      5
BR2    Management   10.20.18.96/29    255.255.255.248  10.20.18.97 - 10.20.18.102         6     6      0
WAN    HQ-BR1       10.20.255.0/31    255.255.255.254  10.20.255.0 - 10.20.255.1          2     2      0
WAN    HQ-BR2       10.20.255.2/31    255.255.255.254  10.20.255.2 - 10.20.255.3          2     2      0
WAN    BR1-BR2      10.20.255.4/31    255.255.255.254  10.20.255.4 - 10.20.255.5          2     2      0

Addresses allocated to segments: 2494 of 65536 in 10.20.0.0/16
Hosts required: 2122; spare addresses inside segments: 372
Summary routes (one per site): BR1 10.20.16.0/23, BR2 10.20.18.0/24, HQ 10.20.0.0/20, WAN 10.20.255.0/24

PASS: no overlaps, every segment fits its site block and its host count
```

Read the result like a reviewer would:
- **Summary routes.** The rest of the network needs only four routes to reach every subnet of Example Corp.
- **Spare column.** BR2 Management has 0 spare addresses: the seventh device will need renumbering. In a real design you would probably give it a /28. There is free space right after it in `10.20.18.0/24`.
- **Room to grow.** HQ uses 2112 of the 4096 addresses in its /20, so `10.20.8.64` to `10.20.15.255` is still free for new HQ segments.

### Step 7 — Find and fix the faults in a broken plan
A colleague sent you this plan. It has several of the faults from the lesson. Save it and run the validator:

```bash
cat > broken.csv <<'EOF'
site,segment,prefix,hosts
HQ,BLOCK,10.20.0.0/20,
HQ,Staff,10.20.0.0/22,900
HQ,Voice,10.20.4.0/24,400
HQ,Guest,10.20.6.0/23,250
HQ,Servers,10.20.7.0/24,200
HQ,Management,10.20.8.0/26,40
BR1,BLOCK,10.20.16.0/23,
BR1,Staff,10.20.16.0/25,120
BR1,Voice,10.20.16.128/26,60
BR1,Guest,10.20.16.192/26,50
BR1,Management,10.20.18.0/28,10
BR2,BLOCK,10.20.18.0/24,
BR2,Staff,10.20.18.0/26,55
BR2,Voice,10.20.18.70/27,25
BR2,Management,10.20.18.96/29,6
WAN,BLOCK,10.20.255.0/24,
WAN,HQ-BR1,10.20.255.0/31,2
WAN,HQ-BR2,10.20.255.2/31,2
WAN,BR1-BR2,10.20.255.4/31,2
EOF
python3 validate_plan.py broken.csv
echo "exit code: $?"
```

Expected output (the end of it):
```text
FAIL: 5 problem(s)
  - BR2/Voice: 10.20.18.70/27 is not a network address (did you mean 10.20.18.64/27?)
  - HQ/Voice: 10.20.4.0/24 has 254 usable addresses but needs 400
  - BR1/Management: 10.20.18.0/28 is outside its site block 10.20.16.0/23
  - overlap: HQ/Guest 10.20.6.0/23 and HQ/Servers 10.20.7.0/24
  - overlap: BR1/Management 10.20.18.0/28 and BR2/Staff 10.20.18.0/26
exit code: 1
```

Copy the file (`cp broken.csv fixed.csv`), edit `fixed.csv` until `python3 validate_plan.py fixed.csv` prints `PASS`, and for each fault write down which lesson rule it breaks. Change as few lines as you can.

> [!TIP]
> Five messages don't always mean five faults. One wrong line can break two rules at once.

<details>
<summary>Show the fixes</summary>

There are four wrong lines:

| Line | Fault | Fix |
|---|---|---|
| `HQ,Voice,10.20.4.0/24,400` | Undersized: a /24 has 254 usable hosts, 400 are needed. | `10.20.4.0/23` |
| `HQ,Guest,10.20.6.0/23,250` | Oversized: the /23 covers `10.20.6.0`–`10.20.7.255` and overlaps Servers. | `10.20.6.0/24` |
| `BR1,Management,10.20.18.0/28,10` | Outside BR1's block (it's in BR2's), so it overlaps BR2 Staff and breaks BR1's summary route. | `10.20.17.0/28` |
| `BR2,Voice,10.20.18.70/27,25` | Not aligned: 70 isn't a multiple of 32. | `10.20.18.64/27` |

After these four changes, `fixed.csv` is identical to the reference `plan.csv`, and you can check it with:

```bash
diff fixed.csv plan.csv && echo "identical"
```

</details>

### Step 8 (optional, Linux, needs sudo) — See a wrong mask break reachability
The validator catches mistakes on paper. This step shows what the same mistake looks like on a live network. You create two **network namespaces** (isolated network stacks on one Linux machine), join them with a virtual Ethernet (veth) cable, and give one side a wrong mask.

Both hosts should be in `198.51.100.0/26`. Host B gets `/28` by mistake, so it thinks its subnet is `198.51.100.32/28` (`.33`–`.46`).

<figure class="diagram" style="--dg-w: 900px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 900 350" width="900" height="350" role="img" aria-labelledby="subnetting-lab-netns-title subnetting-lab-netns-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="subnetting-lab-netns-title">Optional step: two namespaces with a mask mismatch</title>
<desc id="subnetting-lab-netns-desc">Namespace lab-a has veth-a with 198.51.100.10/26 and namespace lab-b has veth-b with 198.51.100.40/28, joined by a veth pair. A believes 198.51.100.0 to .63 is local, so it can reach .40. B believes only .32 to .47 is local, so .10 looks like a remote address with no route and B cannot reply.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="899" height="349" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<rect class="dg-card" x="24" y="24" width="310" height="150" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(40 40) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></g>
<text x="82" y="61" font-size="15" class="dg-text" fill="#17171c" font-weight="700">Namespace lab-a</text>
<text x="42" y="92" font-size="12.5" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">veth-a</text>
<text x="42" y="112" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">198.51.100.10/26</text>
<g class="dg-ok"><rect class="dg-tint" x="42" y="132" width="154" height="26" rx="13" fill="#e8f2ec" stroke="#96c6a8" stroke-width="1.2"/><text x="119" y="149.5" font-size="12" class="dg-ink" fill="#15803d" font-weight="700" text-anchor="middle">/26 · correct mask</text></g>
<rect class="dg-card" x="566" y="24" width="310" height="150" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(582 40) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></g>
<text x="624" y="61" font-size="15" class="dg-text" fill="#17171c" font-weight="700">Namespace lab-b</text>
<text x="584" y="92" font-size="12.5" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">veth-b</text>
<text x="584" y="112" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">198.51.100.40/28</text>
<g class="dg-warn"><rect class="dg-tint" x="584" y="132" width="139" height="26" rx="13" fill="#f8e8e8" stroke="#e09999" stroke-width="1.2"/><text x="653.5" y="149.5" font-size="12" class="dg-ink" fill="#b91c1c" font-weight="700" text-anchor="middle">/28 · wrong mask</text></g>
<path class="dg-line" d="M334 99H566" stroke="#cfcfc8" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<g class="dg-icon-neutral" transform="translate(436 64) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1"/><path d="M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9"/><path d="M21 21v-2h-4"/><path d="M3 5h4V3"/><path d="M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3"/></g>
<rect class="dg-bg-plain" x="357" y="112" width="186" height="24" rx="12" fill="#ffffff"/><text x="450" y="128.5" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="600" text-anchor="middle">veth pair · virtual cable</text>
<text x="60" y="218" font-size="13" class="dg-text" fill="#17171c" font-weight="600">What A thinks is local: 198.51.100.0/26 (.0 – .63)</text>
<text x="60" y="280" font-size="13" class="dg-text" fill="#17171c" font-weight="600">What B thinks is local: 198.51.100.32/28 (.32 – .47). A (.10) is outside, so B can&#x27;t reply</text>
<g class="dg-ok"><rect class="dg-tint" x="60" y="226" width="780" height="26" rx="6" fill="#e3f0e8" stroke="#8ac09e"/></g>
<rect class="dg-card" x="60" y="288" width="780" height="26" rx="6" fill="#ffffff" stroke="#cfcfc8" stroke-dasharray="5 4"/>
<g class="dg-warn"><rect class="dg-tint" x="450" y="288" width="195" height="26" rx="6" fill="#f5dfdf" stroke="#d88282"/></g>
<g class="dg-ok"><path class="dg-stroke" d="M187.969 226V252" stroke="#15803d" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-ok"><circle class="dg-solid" cx="187.969" cy="239" r="9" fill="#15803d"/><text x="187.969" y="243" font-size="11" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">A</text></g>
<g class="dg-ok"><path class="dg-stroke" d="M187.969 288V314" stroke="#15803d" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-ok"><circle class="dg-solid" cx="187.969" cy="301" r="9" fill="#15803d"/><text x="187.969" y="305" font-size="11" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">A</text></g>
<g class="dg-warn"><path class="dg-stroke" d="M553.594 226V252" stroke="#b91c1c" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><circle class="dg-solid" cx="553.594" cy="239" r="9" fill="#b91c1c"/><text x="553.594" y="243" font-size="11" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">B</text></g>
<g class="dg-warn"><path class="dg-stroke" d="M553.594 288V314" stroke="#b91c1c" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><circle class="dg-solid" cx="553.594" cy="301" r="9" fill="#b91c1c"/><text x="553.594" y="305" font-size="11" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">B</text></g>
<text x="60" y="334" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">.0</text>
<path class="dg-line" d="M60 316V322" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<text x="255" y="334" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">.16</text>
<path class="dg-line" d="M255 316V322" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<text x="450" y="334" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">.32</text>
<path class="dg-line" d="M450 316V322" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<text x="645" y="334" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">.48</text>
<path class="dg-line" d="M645 316V322" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<text x="840" y="334" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">.63</text>
<path class="dg-line" d="M840 316V322" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
</svg></figure>

*Figure 2. The same wire, two different views of the subnet. A can reach B, but B treats A's address as remote and has no route to reply.*

Create the namespaces, the cable and the addresses:

```bash
sudo ip netns add lab-a
sudo ip netns add lab-b
sudo ip link add veth-a type veth peer name veth-b
sudo ip link set veth-a netns lab-a
sudo ip link set veth-b netns lab-b
sudo ip -n lab-a addr add 198.51.100.10/26 dev veth-a
sudo ip -n lab-b addr add 198.51.100.40/28 dev veth-b
sudo ip -n lab-a link set veth-a up
sudo ip -n lab-b link set veth-b up
sudo ip -n lab-b route
```

Expected output (the routing table of `lab-b`):
```text
198.51.100.32/28 dev veth-b proto kernel scope link src 198.51.100.40
```

Host B only considers `198.51.100.32/28` local. `198.51.100.10` is outside it, and B has no other route.

Ping in both directions:

```bash
sudo ip netns exec lab-a ping -c 2 198.51.100.40
sudo ip netns exec lab-b ping -c 2 198.51.100.10
```

Expected output (timings vary):
```text
PING 198.51.100.40 (198.51.100.40) 56(84) bytes of data.
From 198.51.100.10 icmp_seq=1 Destination Host Unreachable
From 198.51.100.10 icmp_seq=2 Destination Host Unreachable

--- 198.51.100.40 ping statistics ---
2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 1026ms
pipe 2
ping: connect: Network is unreachable
```

The two sides fail differently:
- **From A**, `.40` looks local (A's mask is right), so A sends an ARP request. B doesn't answer, because it has no route back to `198.51.100.10`. With no ARP reply, A reports `Destination Host Unreachable`.
- **From B**, `.10` is outside its `/28` and there's no default route, so the kernel refuses to send at all: `Network is unreachable`.

Now try to give B a default gateway that is outside its (wrong) subnet:

```bash
sudo ip -n lab-b route add default via 198.51.100.1
```

Expected output:
```text
Error: Nexthop has invalid gateway.
```

Linux refuses a gateway that isn't on a directly connected subnet. That's the "gateway outside the subnet" fault from the lesson.

Fix the mask and test again:

```bash
sudo ip -n lab-b addr del 198.51.100.40/28 dev veth-b
sudo ip -n lab-b addr add 198.51.100.40/26 dev veth-b
sudo ip netns exec lab-a ping -c 2 198.51.100.40
```

Expected output (timings vary):
```text
PING 198.51.100.40 (198.51.100.40) 56(84) bytes of data.
64 bytes from 198.51.100.40: icmp_seq=1 ttl=64 time=0.040 ms
64 bytes from 198.51.100.40: icmp_seq=2 ttl=64 time=0.047 ms

--- 198.51.100.40 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1034ms
rtt min/avg/max/mdev = 0.040/0.043/0.047/0.003 ms
```

> [!NOTE]
> The outputs above come from iproute2 6.17 and iputils 20250605. Other versions word messages slightly differently, and a non-English locale translates them; run commands with `LC_ALL=C` for English output. The routing behaviour is the same.

## Verification
You have completed the lab when:

1. Your own plan passes:
   ```bash
   python3 validate_plan.py plan.csv; echo "exit code: $?"
   ```
   The output ends with `PASS: ...` and `exit code: 0`.
2. Your fixed version of the broken plan passes:
   ```bash
   python3 validate_plan.py fixed.csv; echo "exit code: $?"
   ```
   The output ends with `PASS: ...` and `exit code: 0`.
3. You can name the lesson rule behind each of the four faults in Step 7.
4. (Optional Step 8) With the mask fixed, `sudo ip netns exec lab-a ping -c 2 198.51.100.40` shows `0% packet loss`.

## Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError: 'segment'` (or `'site'`, `'prefix'`, `'hosts'`) | The CSV header line is missing or misspelled. | Make the first line exactly `site,segment,prefix,hosts`. |
| `ValueError: invalid literal for int() with base 10: ''` | A segment row has an empty `hosts` column. | Only `BLOCK` rows may leave `hosts` empty. |
| `... is not a network address (did you mean ...?)` | The prefix has host bits set: it doesn't start on its own boundary. | Use the suggested network, then re-check it doesn't overlap a neighbour. |
| `... is outside its site block ...` | A segment was placed in another site's block, or the site block is too small. | Move the segment into its own block, or choose a bigger aligned site block. |
| `RTNETLINK answers: Operation not permitted` | You ran an `ip` command that changes the network without `sudo`. | Prefix the command with `sudo`. |
| `Cannot open network namespace "lab-a": No such file or directory` | The namespace doesn't exist (a step was skipped, or cleanup already ran). | Run `ip netns list`, then repeat the creation commands of Step 8. |
| `File exists` when creating a namespace or the veth pair | Leftovers from an earlier attempt. | Run the [Cleanup](#cleanup) commands, then start Step 8 again. |

## Challenge (optional)
Example Corp opens a third branch, BR3, with Staff (200 hosts), Voice (100) and Management (10), plus a WAN link to HQ. Add it to your plan without renumbering anything. Then make the plan even tidier: choose BR3's block so that **all branches** together (BR1, BR2 and BR3) can be advertised to HQ as one summary route. Which route is it, and how much room does it leave for future branches? Confirm with the validator.

## Cleanup
Remove the lab files:

```bash
cd ~
rm -r ~/subnet-lab
```

If you did Step 8, delete both namespaces. Deleting a namespace also deletes the veth interface inside it, and deleting one end of a veth pair deletes the other.

```bash
sudo ip netns del lab-a
sudo ip netns del lab-b
ip netns list
```

Expected output: `ip netns list` prints nothing (or doesn't list `lab-a` or `lab-b`).

## What you learned
- Sizing first, then placing: each segment's prefix comes from its host count, and each site's block from the sum of its segments, rounded up to a power of two.
- Allocating largest first on aligned boundaries packs subnets with no holes and keeps every site summarizable as one route.
- Overlaps, undersized subnets and misaligned prefixes are easy to miss by eye and easy to catch with a script.
- On a live host, a wrong mask breaks reachability asymmetrically, and Linux refuses a default gateway outside the host's subnet.