'Generate an IP address from the set of available addresses.'

def _generate_ip(self, context, prefer_next=False):

    ip_allocations = netaddr.IPSet()
    for ipallocation in self.subnet_manager.list_allocations(context):
        ip_allocations.add(ipallocation.ip_address)
    for ip_pool in self.subnet_manager.list_pools(context):
        ip_set = netaddr.IPSet()
        ip_set.add(netaddr.IPRange(ip_pool.first_ip, ip_pool.last_ip))
        av_set = ip_set.difference(ip_allocations)
        if (av_set.size == 0):
            continue
        if prefer_next:
            window = 1
        else:
            window = min(av_set.size, 10)
        ip_index = random.randint(1, window)
        candidate_ips = list(itertools.islice(av_set, ip_index))
        allocated_ip = candidate_ips[(-1)]
        return (str(allocated_ip), ip_pool.id)
    raise ipam_exc.IpAddressGenerationFailure(subnet_id=self.subnet_manager.neutron_id)
