A minimal DHCP-style IP address allocator written in Python. It assigns host IPs from a given IPv4/IPv6 subnet, tracks which addresses are in use, and releases them on request.
- Python 3.10+ (uses PEP 604
X | Noneunions and built-inset[...]generics) - No third-party dependencies — only the standard-library
ipaddressmodule
from main import DHCP
dhcp = DHCP("192.168.1.0/29")
# Allocate a single address
ip = dhcp.allocate()
# Allocate several at once (stops early if the pool is exhausted)
ips = dhcp.allocate_multiple(5)
# Release an address back to the pool
dhcp.release("192.168.1.1")
# Validate a string as an IP address
DHCP.is_valid_ip("192.168.1.10") # TrueRun the built-in demo:
python main.pyExpected output (for the 192.168.1.0/29 subnet, which has 6 usable hosts):
['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4', '192.168.1.5']
True
Create an allocator bound to the given subnet (e.g. "192.168.1.0/29" or an IPv6 network). The network object is stored on self.network and the set of allocated addresses on self.allocated.
Return the first unused host address in the subnet, marking it as allocated. Returns None if the pool is exhausted.
Allocate up to count addresses and return them as strings. The returned list is shorter than count when the pool runs out mid-way.
Release a previously allocated address. Returns True if the address was allocated and has now been freed, False if it was not in the allocated set.
Static helper that returns True if ip parses as a valid IPv4 or IPv6 address.
- Allocation scans
network.hosts()from the start on every call, so it is O(n) per allocation. Fine for small subnets, not ideal for large ones. - State is held entirely in memory — nothing is persisted between runs.
- The class does not implement the DHCP wire protocol; it only models the address-pool bookkeeping a DHCP server would do.