~/problems / Bit manipulation

IPv4 / CIDR iterator

medium 5 levels ~75 min OpenAI

Level 1 Forward iteration

Build an iterator over IPv4 addresses.

IPV4Iterator(ip) takes a dotted address like "10.0.0.254". Iterating it yields address strings starting at ip and counting up, one at a time, through "255.255.255.255", then raises StopIteration. __iter__ returns the iterator itself, so list(it) and next(it) both work.

it = IPV4Iterator("10.0.0.254")
next(it)   # "10.0.0.254"
next(it)   # "10.0.0.255"
next(it)   # "10.0.1.0"   (carry into the next octet)

list(IPV4Iterator("255.255.255.253"))
# ["255.255.255.253", "255.255.255.254", "255.255.255.255"]

Store the cursor as a 32-bit integer and format it only when you return it; string arithmetic on octets is where the carry bugs come from. The iterator must be lazy: IPV4Iterator("0.0.0.0") covers four billion addresses, so don't build a list up front. Don't use the ipaddress module.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Level 4 unlocks when level 3 passes.

Level 5 unlocks when level 4 passes.

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc