Planning IP addresses for your local area network

If you are wondering how to pick up a suitable IP subnet, try the ipaddress module. The following code snippet shows an example of how to choose a specific subnet, based on the number of necessary host IP addresses for a small private network.

Suppose you have a CIDR network address, such as 192.168.0.0/24, and you want to generate a range of all the IP addresses that it represents (192.168.0.1 to 192.168.0.254). The ipaddress module can be easily used to perform such calculations:

>>> import ipaddress
>>> net = ipaddress.ip_network('192.168.0.0/24')
>>> net
IPv4Network('192.168.0.0/24')
>>> for a in net:
... print(a)
...
192.168.0.1
192.168.0.2
192.168.0.3
...
192.168.0.254

In this example, we are using the ip_network method from the ipaddress module to generate a range of all the IP addresses that represent the network.

You can find the following code in the net_ip_planner.py file:

!/usr/bin/env python3

import ipaddress as ip

CLASS_C_ADDR = '192.168.0.0'

mask = input("Enter the mask len (24-30): ")
mask = int(mask)
if mask not in range(23, 31):
raise Exception("Mask length must be between 24 and 30")

net_addr = CLASS_C_ADDR + '/' + str(mask)
print("Using network address:%s " %net_addr)

try:
network = ip.ip_network(net_addr)
except:
raise Exception("Failed to create network object")

print("This mask will give %s IP addresses" %(network.num_addresses))
print("The network configuration will be:")
print(" network address: %s" %str(network.network_address))
print(" netmask: %s" %str(network.netmask))
print(" broadcast address: %s" %str(network.broadcast_address))
first_ip, last_ip = list(network.hosts())[0], list(network.hosts())[-1]
print(" host IP addresses: from %s to %s" %(first_ip,last_ip))

The following is the execution of the previous script for some masks and the C class IP address, 192.168.0.0:

  • Execution with mask 24:
Enter the mask len (24-30): 24
Using network address:192.168.0.0/24
This mask will give 256 IP addresses
The network configuration will be:
network address: 192.168.0.0
netmask: 255.255.255.0
broadcast address: 192.168.0.255
host IP addresses: from 192.168.0.1 to 192.168.0.254
  • Execution with mask 30:
Enter the mask len (24-30): 30
Using network address:192.168.0.0/30
This mask will give 4 IP addresses
The network configuration will be:
network address: 192.168.0.0
netmask: 255.255.255.252
broadcast address: 192.168.0.3
host IP addresses: from 192.168.0.1 to 192.168.0.2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset