How to Calculate VPC Subnet CIDR Details in Python
Compute network address, broadcast address, address count, prefix length, and netmask for any IPv4 CIDR using the Python standard library's ipaddress module.
Python code
20 linesimport ipaddress
def subnet_details(cidr: str) -> dict:
network = ipaddress.ip_network(cidr, strict=False)
return {
"network_address": str(network.network_address),
"broadcast_address": str(network.broadcast_address),
"num_addresses": network.num_addresses,
"prefix_length": network.prefixlen,
"netmask": str(network.netmask),
}
if __name__ == "__main__":
for cidr in ["10.0.0.0/24", "172.16.0.0/20", "192.168.1.0/28"]:
details = subnet_details(cidr)
print(f"{cidr}: {details['num_addresses']} addresses, "
f"net {details['network_address']} - "
f"broadcast {details['broadcast_address']}, mask {details['netmask']}")
Output
10.0.0.0/24: 256 addresses, net 10.0.0.0 - broadcast 10.0.0.255, mask 255.255.255.0
172.16.0.0/20: 4096 addresses, net 172.16.0.0 - broadcast 172.16.15.255, mask 255.255.240.0
192.168.1.0/28: 16 addresses, net 192.168.1.0 - broadcast 192.168.1.15, mask 255.255.255.240
How it works
The ipaddress.ip_network function parses a CIDR string into an IPv4Network object. With strict=False, it accepts network addresses with host bits set, which is useful when checking VPC subnets from user input. The network_address and broadcast_address properties give the boundaries, while num_addresses counts total addresses (including network and broadcast). prefixlen yields the CIDR prefix length, and netmask gives the dotted-decimal mask. This pattern is ideal for validating or planning AWS VPC subnet allocations.
Common mistakes
- Using `strict=True` (default) which raises an error when host bits are set in the network address
- Forgetting that `num_addresses` includes network and broadcast addresses, not just usable hosts
- Trying to access `broadcast_address` on a /31 or /32 subnet where it doesn't exist
- Assuming the module returns a string for netmask; it's an integer address object until converted with `str()`
Variations
- Use `network.hosts()` or compute `num_addresses - 2` to get usable host count for routine subnets
- Iterate over `network.subnets(new_prefix=26)` to split a VPC CIDR into smaller subnets
Real-world use cases
- Validating a user-provided CIDR before creating an AWS VPC or subnet in a CloudFormation script.
- Calculating how many IP addresses are available in a VPC CIDR to plan service deployment capacity.
- Enumerating subnets of a larger CIDR block to allocate isolated network segments for different environments.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.