Skip to content

Instantly share code, notes, and snippets.

@NightBlues
Created December 22, 2016 16:09
Show Gist options
  • Save NightBlues/bf92f649611d03d882bf8d4633ffb7c5 to your computer and use it in GitHub Desktop.
Save NightBlues/bf92f649611d03d882bf8d4633ffb7c5 to your computer and use it in GitHub Desktop.
import IPy
def gen_next_net(cidr):
"""
>>> from IPy import IP
>>> get_next_net(IP("10.0.0.0/28"))
IP('10.0.0.16/28')
>>> reduce(lambda acc, _: get_next_net(acc), range(10), IP("10.0.0.0/28"))
IP('10.0.0.160/28')
"""
return IPy.IP(cidr.broadcast().int() + 1).make_net(cidr.netmask())
def find_next_subnet(subnets):
"""Return next available cidr for subnet.
:param [string] subnets: cidrs
:returns: cidr
:rtype: string
"""
subnets = map(IPy.IP, subnets)
subnets_29 = [net for net in subnets if net.len() == 8]
subnet = IPy.IP("10.194.167.240/29") # '0xac2a7f0'
if len(subnets_29) != 0:
subnet = sorted(subnets_29)[-1]
def _check_cidr(cidr):
if cidr.iptype() != 'PRIVATE':
return False
for subnet in subnets:
if subnet.overlaps(cidr):
return False
return True
for _ in range(100):
subnet = gen_next_net(subnet)
if _check_cidr(subnet):
break
else:
raise Exception("Can not choose next cidr for subnets.")
return str(subnet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment