Skip to content

Instantly share code, notes, and snippets.

@Patrick-Kelley
Created April 21, 2023 12:36
Show Gist options
  • Save Patrick-Kelley/d9c33d382afc8a411146c7d4a0486648 to your computer and use it in GitHub Desktop.
Save Patrick-Kelley/d9c33d382afc8a411146c7d4a0486648 to your computer and use it in GitHub Desktop.
# Python script to convert subnets to lists of IP
# Prompt the user to input a subnet in CIDR notation
subnet = input("Enter the subnet in CIDR notation (e.g. 192.168.1.0/24): ")
# Split the subnet into IP address and CIDR mask
ip_addr, cidr = subnet.split("/")
cidr = int(cidr)
# Calculate the netmask
netmask = (0xffffffff << (32 - cidr)) & 0xffffffff
# Calculate the starting and ending IP addresses
start_ip = int(''.join(['%02x' % int(x) for x in ip_addr.split('.')]), 16) & netmask
end_ip = start_ip | ~netmask & 0xffffffff
# Iterate over all IP addresses in the subnet and append them to a list
ips = []
for i in range(start_ip, end_ip+1):
ips.append('.'.join([str((i >> (8 * j)) & 0xff) for j in range(4)][::-1]))
# Print out the list of IP addresses with each IP address on a separate line
print('\n'.join(ips))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment