Foundation project

Project: plan an office network

Lesson 8 of 20 · 18 min · Module 2: Python’s ipaddress toolkit

A new office needs separate networks for guests, staff, and printers, each sized to fit. Plan the allocation automatically, like a network engineer using VLSM (variable-length subnet masks).

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Size a subnet for a number of hosts
  • Allocate subnets in a safe order
  • Detect when a plan does not fit

The idea

Give the largest needs the first, largest subnets. For a team that needs n hosts, the smallest prefix that fits is 32 - (n + 2 - 1).bit_length(): room for n devices plus the network and broadcast addresses. Allocating largest first keeps every subnet aligned.

for hosts in (10, 50, 100):
    print(hosts, 32 - (hosts + 1).bit_length())

01From hosts to prefix

50 hosts need 52 addresses. The next power of two is 64 = 2^6, so the subnet needs 6 host bits: a /26. (50 + 1).bit_length() is 6, so the prefix is 32 - 6 = 26.

print((50 + 1).bit_length())
Output
6

02Largest first keeps alignment

A /26 must start at a multiple of 64. Placing the biggest subnets first means every later, smaller subnet starts on a boundary that suits it.

03Track a cursor

Keep the next free address as an integer. After each allocation, add the subnet size. If the last address of a new subnet would pass the end of the base network, the plan does not fit.

Your project brief

Write plan_subnets(base, needs). base is an IPv4 CIDR string and needs maps a team name to the number of hosts it needs (at least 1). Allocate subnets from the start of base, largest need first (ties by team name), each as small as possible. Return a dict mapping each team to its CIDR string. Raise ValueError if the teams do not fit.

What the checks look for

  • Plans guests, staff and printers in a /24
  • Uses the smallest subnet that fits exactly
  • Breaks ties by team name
  • Raises ValueError when the teams do not fit
Try it in the editor →

Take this with you

Size by hosts + 2, allocate largest first, and check the remaining space every time.

Go a little further

Return the unused space at the end as a list of free CIDR blocks.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →