How to calculate the number of subnets in a CIDR block

The aim of this page📝 is to explain how to calculate the number of /24 subnets in a CIDR block based on the example of the VPC CIDR block 10.100.0.0/16. I got to this topic as I was listening to the great episode SE Radio 586: Nikhil Shetty on Virtual Private Cloud : Software Engineering Radio

Pavol Kutaj
2 min readOct 27, 2023
  • A CIDR block is a range of IP addresses that is identified by a network address and a subnet mask. The subnet mask determines how many bits of the IP address are used to identify the network and how many bits are used to identify the host.
  • E.g. a/24 CIDR block is a CIDR block with a subnet mask of 255.255.255.0. This means that the first 24 bits of the IP address are used to identify the network and the last 8 bits are used to identify the host.
  • To calculate the number of /24 subnets in a CIDR block, we can use the following formula:
Number of subnets = 2^(subnet mask bits - network mask bits)
  • For example, the VPC CIDR block 10.100.0.0/16 has a subnet mask of 255.255.0.0. This means that the first 16 bits of the IP address are used to identify the network and the last 16 bits are used to identify the host.
  • Therefore, the number of /24 subnets in the VPC CIDR block 10.100.0.0/16 is:
Number of subnets = 2^(24 - 16) = 256

CODE

import ipaddress

def get_num_subnets(cidr_block:str, subnet_mask:int) -> int:
"""Calculates the number of possible subnets within a CIDR block.

Args:
cidr_block: A network CIDR block in string format.
subnet_mask: A subnet mask defining the size of subnets within networks

Returns:
The number subnets in the CIDR block.
"""

network = ipaddress.IPv4Network(cidr_block, subnet_mask)
network_mask = network.prefixlen
num_subnets = 2**(subnet_mask - network_mask)
return num_subnets

# Example usage:

num_subnets = get_num_subnets("10.100.0.0/16", 24)

print(num_subnets)

Output:

256

LINKS

--

--

No responses yet