3. Subnetting & CIDR Calculation
Subnetting Fundamentals
Subnetting is the process of partitioning a single physical network into multiple smaller logical networks. At its core, an IPv4 address is 32 bits long, divided into a network portion and a host portion by the Subnet Mask.
The Subnet Mask is a 32-bit number that acts like a filter. Where the mask has bits set to 1, the IP address bit is part of the network address. Where it has 0s, it is part of the host range. For example, a 255.255.255.0 mask indicates the first 24 bits are the network.
To verify this in the terminal, you can analyze your local interface configuration or capture packets to inspect headers.
ip addr show eth0 | grep 'inet ' | awk '{print $2}'
CIDR Notation Explained
CIDR (Classless Inter-Domain Routing) replaces the older class-based system (A, B, C) with a concise notation. The suffix /n represents the number of leading 1-bits in the subnet mask.
For example, a /24 means 24 ones followed by 8 zeros (255.255.255.0). A /30 is often used for point-to-point links between routers as it only provides 2 usable host addresses.
Use the dig command or ipcalc if installed to perform quick network arithmetic on your system.
nmap -sL 192.168.1.0/24 | grep 'Nmap scan report for'
Calculating Host Capacities
To calculate capacity, we convert the CIDR prefix to the total number of bits remaining for hosts. If you have a /27, you have 32 - 27 = 5 bits for hosts. 2 to the power of 5 is 32. Subtracting the network and broadcast addresses leaves 30 usable hosts.
This is essential for security scoping. When segmenting an environment, never overallocate. Use the smallest possible subnet to minimize the 'blast radius' of a potential compromise.
import math def calculate_hosts(prefix): host_bits = 32 - prefix total_hosts = 2**host_bits usable_hosts = total_hosts - 2 return usable_hosts print(f'Usable hosts for /24: {calculate_hosts(24)}')
Building a Python CIDR Utility
We can create a professional-grade script to automate the calculation of network ranges using the ipaddress module. This is critical for SOC analysts who need to identify if an IP falls within a malicious subnet block.
The script below takes a CIDR string and returns the network and broadcast boundaries.
ipaddress library in Python is significantly safer and more accurate than manual bit-shifting.
import ipaddress def get_network_details(cidr): net = ipaddress.ip_network(cidr, strict=False) return { 'network': str(net.network_address), 'broadcast': str(net.broadcast_address), 'hosts': list(net.hosts()) } info = get_network_details('10.0.0.0/29') print(f'Network: {info['network']}') print(f'Broadcast: {info['broadcast']}')
Knowledge Check
Ready to test your understanding of 3. Subnetting & CIDR Calculation?