Last modified: Apr 27, 2025 By Alexander Williams

Subnet IP Address Using Python Guide

Subnetting is a key skill for network engineers. It helps divide networks into smaller parts. Python makes subnetting easy with its built-in libraries.

What Is Subnetting?

Subnetting splits a large network into smaller subnetworks. This improves security and performance. Each subnet has its own range of IP addresses.

Subnets use CIDR notation (Classless Inter-Domain Routing). For example, 192.168.1.0/24 means 256 addresses. The /24 shows the subnet mask length.

Required Python Libraries

Python's ipaddress module handles IP addresses and subnets. It comes built-in with Python 3. No installation is needed.

First, import the module:

 
import ipaddress

This module can validate IPv4 and IPv6 addresses. It also performs subnet calculations.

Creating a Network Object

Use ipaddress.IPv4Network to create a network object. Pass the IP address with CIDR notation.

 
network = ipaddress.IPv4Network('192.168.1.0/24')

This creates a network object for the 192.168.1.0/24 subnet. The object contains all subnet details.

Getting Subnet Details

The network object provides useful properties:

 
print("Network Address:", network.network_address)
print("Broadcast Address:", network.broadcast_address)
print("Netmask:", network.netmask)
print("Hosts:", network.num_addresses)


Network Address: 192.168.1.0
Broadcast Address: 192.168.1.255
Netmask: 255.255.255.0
Hosts: 256

These properties help understand the subnet range. The num_addresses shows total available IPs.

Splitting a Network into Subnets

Use subnets() to divide a network. Specify the new prefix length for smaller subnets.

 
subnets = list(network.subnets(prefixlen_diff=2))
print("Subnets:", len(subnets))
for subnet in subnets:
    print(subnet)


Subnets: 4
192.168.1.0/26
192.168.1.64/26
192.168.1.128/26
192.168.1.192/26

The prefixlen_diff=2 creates 4 smaller subnets (/26). Each has 64 IP addresses.

Checking IP Address Membership

Use the in operator to check if an IP belongs to a subnet. This is useful for access control.

 
ip = ipaddress.IPv4Address('192.168.1.10')
print(ip in network)


True

The output shows 192.168.1.10 is in the 192.168.1.0/24 network. This method is fast and reliable.

Handling Errors

Invalid inputs raise exceptions. Always use try-except blocks. This prevents crashes.

 
try:
    bad_network = ipaddress.IPv4Network('192.168.1.300/24')
except ipaddress.AddressValueError as e:
    print("Error:", e)


Error: 192.168.1.300/24 has host bits set

Proper error handling makes your code robust. It also helps debug issues faster.

Practical Example: Subnet Calculator

Let's build a simple subnet calculator. It takes an IP range and splits it.

 
def subnet_calculator(ip_range, new_prefix):
    try:
        network = ipaddress.IPv4Network(ip_range)
        subnets = list(network.subnets(new_prefix=new_prefix))
        for i, subnet in enumerate(subnets, 1):
            print(f"Subnet {i}: {subnet}")
    except ValueError as e:
        print(f"Invalid input: {e}")

subnet_calculator('10.0.0.0/16', 18)


Subnet 1: 10.0.0.0/18
Subnet 2: 10.0.64.0/18
Subnet 3: 10.0.128.0/18
Subnet 4: 10.0.192.0/18

This function is reusable. It helps visualize subnet divisions clearly.

Conclusion

Python's ipaddress module simplifies subnetting. It handles CIDR notation, subnet splitting, and IP validation.

You can build tools for network management. These tools automate complex calculations. Always validate inputs to avoid TypeError exceptions.

For more Python networking, see how to handle ZMQ messages. Or learn about file path manipulation with pathlib.