Python – IP Subnetting

# Author: Kerry Cordero
# Version: 1.0.0
# Description: This script prompt for the IP Address and then the SubnetMask/CIDR.  It will output the Network Address, CIDR, Usable IP Range, Broadcast Address, Subnet Mask, and Total Usable IPs.


from prettytable import PrettyTable
import ipaddress

def subnet_calculation(ip_address, subnet):
    # Convert the IP address to IPv4Network object
    network = ipaddress.IPv4Network(f"{ip_address}/{subnet}", strict=False)

    # Calculate the network address
    network_address = str(network.network_address)

    # Calculate the broadcast address
    broadcast_address = str(network.broadcast_address)

    # Calculate the CIDR notation
    cidr_notation = f"{network_address}/{subnet}"

    # Calculate the usable IP range
    usable_ips = list(network.hosts())
    start_ip = str(usable_ips[0])
    end_ip = str(usable_ips[-1])
    
    # Calculate the total number of usable IPs
    total_usable_ips = len(usable_ips)  # Only count usable addresses

    # Create a PrettyTable and add rows
    table = PrettyTable()
    table.field_names = ["Network Address", "CIDR", "Usable IP Range", "Broadcast Address", "Subnet Mask", "Total Usable"]
    table.add_row([network_address, cidr_notation, f"{start_ip} - {end_ip}", broadcast_address, str(network.netmask), total_usable_ips])

    return table

# Prompt the user for the IP address
ip_address = input("Enter the IP address: ")

# Prompt the user for the subnet
subnet_input = input("Enter the subnet (in CIDR notation or full write out): ")

# Extract the subnet prefix length from the input
if "/" in subnet_input:
    subnet = int(subnet_input.split("/")[1])
else:
    # Use the subnet mask to generate a dummy IPv4Interface object, then get its network's prefix length
    dummy_interface = ipaddress.IPv4Interface(f"0.0.0.0/{subnet_input}")
    subnet = dummy_interface.network.prefixlen

# Call the subnet_calculation function
result_table = subnet_calculation(ip_address, subnet)

# Print the result table
print(result_table)