How to use the netaddr.all_matching_cidrs function in netaddr

To help you get started, we’ve selected a few netaddr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github drkjam / netaddr / test / ip / test_cidr_v4.py View on Github external
def test_all_matching_cidrs_v4():
    assert all_matching_cidrs('192.0.2.32', ['0.0.0.0/0', '10.0.0.0/8', '192.0.0.0/8', '192.0.1.0/24', '192.0.2.0/24', '192.0.3.0/24']) == [
        IPNetwork('0.0.0.0/0'),
        IPNetwork('192.0.0.0/8'),
        IPNetwork('192.0.2.0/24'),
    ]
github opennode / opennode-knot / opennode / knot / model / compute.py View on Github external
from opennode.knot.model.virtualizationcontainer import IVirtualizationContainer
        p = sudo(self.context)
        if (IVirtualCompute.providedBy(p) and
                IVirtualizationContainer.providedBy(p.__parent__)):
            res.append(u'virt_type:' + p.__parent__.backend)
            res.append(u'virt:yes')
        else:
            res.append(u'virt:no')

        config = get_config()
        if config.has_section('netenv-tags'):
            for tag, nets in config.items('netenv-tags'):
                try:
                    if (self.context.ipv4_address is not None and
                        len(netaddr.all_matching_cidrs(self.context.ipv4_address.split('/')[0],
                                                       nets.split(','))) > 0):
                        res.append(u'env:' + tag)
                except ValueError:
                    # graceful ignoring of incorrect ips
                    pass
        return res
github openstack / neutron / neutron / db / l3_db.py View on Github external
router_subnets.append(ip['subnet_id'])

        # Ignore temporary Prefix Delegation CIDRs
        new_subnets = [s for s in new_subnets
                       if s['cidr'] != constants.PROVISIONAL_IPV6_PD_PREFIX]
        id_filter = {'id': router_subnets}
        subnets = self._core_plugin.get_subnets(context.elevated(),
                                                filters=id_filter)
        for sub in subnets:
            cidr = sub['cidr']
            ipnet = netaddr.IPNetwork(cidr)
            for s in new_subnets:
                new_cidr = s['cidr']
                new_ipnet = netaddr.IPNetwork(new_cidr)
                match1 = netaddr.all_matching_cidrs(new_ipnet, [cidr])
                match2 = netaddr.all_matching_cidrs(ipnet, [new_cidr])
                if match1 or match2:
                    data = {'subnet_cidr': new_cidr,
                            'subnet_id': s['id'],
                            'cidr': cidr,
                            'sub_id': sub['id']}
                    msg = (_("Cidr %(subnet_cidr)s of subnet "
                             "%(subnet_id)s overlaps with cidr %(cidr)s "
                             "of subnet %(sub_id)s") % data)
                    raise n_exc.BadRequest(resource='router', msg=msg)
github openstack / neutron / neutron / ipam / subnet_alloc.py View on Github external
def _allocate_specific_subnet(self, request):
        with db_api.CONTEXT_WRITER.using(self._context):
            self._lock_subnetpool()
            self._check_subnetpool_tenant_quota(request.tenant_id,
                                                request.prefixlen)
            cidr = request.subnet_cidr
            available = self._get_available_prefix_list()
            matched = netaddr.all_matching_cidrs(cidr, available)
            if len(matched) == 1 and matched[0].prefixlen <= cidr.prefixlen:
                return IpamSubnet(request.tenant_id,
                                  request.subnet_id,
                                  cidr,
                                  gateway_ip=request.gateway_ip,
                                  allocation_pools=request.allocation_pools)
            msg = _("Cannot allocate requested subnet from the available "
                    "set of prefixes")
            raise exceptions.SubnetAllocationError(reason=msg)
github openstack / tricircle / juno-patches / neutron / neutron_cascaded_l3_patch / neutron / db / extraroute_db.py View on Github external
def _validate_routes_nexthop(self, cidrs, ips, routes, nexthop):
        #Note(nati): Nexthop should be connected,
        # so we need to check
        # nexthop belongs to one of cidrs of the router ports
        extern_relay_cidr = cfg.CONF.l3gw_extern_net_ip_range
        if not netaddr.all_matching_cidrs(nexthop, cidrs):
            if(cfg.CONF.cascade_str == 'cascaded'
               and extern_relay_cidr
               and netaddr.all_matching_cidrs(nexthop,
                                              [extern_relay_cidr])):
                LOG.debug(_('nexthop(%s) is in extern_relay_cidr,'
                            'so not raise InvalidRoutes exception'), nexthop)
                return
            raise extraroute.InvalidRoutes(
                routes=routes,
                reason=_('the nexthop is not connected with router'))
        #Note(nati) nexthop should not be same as fixed_ips
        if nexthop in ips:
            raise extraroute.InvalidRoutes(
                routes=routes,
                reason=_('the nexthop is used by router'))
github openstack / tricircle / juno-patches / neutron / neutron_cascaded_l3_patch / neutron / db / extraroute_db.py View on Github external
def _make_extra_route_list(extra_routes):
        # added by j00209498  ----begin
        extern_relay_cidr = cfg.CONF.l3gw_extern_net_ip_range
        if(cfg.CONF.cascade_str == 'cascaded' and extern_relay_cidr):
            routes_list = []
            for route in extra_routes:
                if(netaddr.all_matching_cidrs(route['nexthop'],
                                              [extern_relay_cidr])):
                    routes_list.append({'destination': route['destination'],
                                        'nexthop': route['nexthop'],
                                        'onlink': True})
                else:
                    routes_list.append({'destination': route['destination'],
                                        'nexthop': route['nexthop']})
            return routes_list
        # added by j00209498  ----end
        return [{'destination': route['destination'],
                 'nexthop': route['nexthop']}
                for route in extra_routes]
github saltstack / salt-cloud / salt_cloud / saltcloud / clouds / openstack.py View on Github external
def ignore_cidr(vm_, ip):
    '''
    Return True if we are to ignore the specified IP. Compatible with IPv4.
    '''
    if HAS_NETADDR is False:
        log.error('Error: netaddr is not installed')
        return 'Error: netaddr is not installed'

    cidr = config.get_config_value(
        'ignore_cidr', vm_, __opts__, default='', search_global=False
    )
    if cidr != '' and all_matching_cidrs(ip, [cidr]):
        log.warning("IP '%s' found within '%s'; ignoring it.'" % (ip, cidr))
        return True

    return False
github Juniper / contrail-neutron-plugin / neutron_plugin_contrail / plugins / opencontrail / ctdb / config_db.py View on Github external
rports = self.port_list(filters={'device_id': [router_id]})
            # It's possible these ports are on the same network, but
            # different subnets.
            new_ipnet = netaddr.IPNetwork(subnet_cidr)
            for p in rports:
                for ip in p['q_api_data']['fixed_ips']:
                    if ip['subnet_id'] == subnet_id:
                        msg = (_("Router already has a port on subnet %s")
                               % subnet_id)
                        raise exceptions.BadRequest(resource='router', msg=msg)
                    sub_id = ip['subnet_id']
                    subnet = self.subnet_read(sub_id)['q_api_data']
                    cidr = subnet['cidr']
                    ipnet = netaddr.IPNetwork(cidr)
                    match1 = netaddr.all_matching_cidrs(new_ipnet, [cidr])
                    match2 = netaddr.all_matching_cidrs(ipnet, [subnet_cidr])
                    if match1 or match2:
                        data = {'subnet_cidr': subnet_cidr,
                                'subnet_id': subnet_id,
                                'cidr': cidr,
                                'sub_id': sub_id}
                        msg = (_("Cidr %(subnet_cidr)s of subnet "
                                 "%(subnet_id)s overlaps with cidr %(cidr)s "
                                 "of subnet %(sub_id)s") % data)
                        raise exceptions.BadRequest(resource='router', msg=msg)
        except NoIdError:
            pass
github saltstack / salt / salt / cloud / clouds / openstack.py View on Github external
def ignore_cidr(vm_, ip):
    '''
    Return True if we are to ignore the specified IP. Compatible with IPv4.
    '''
    if HAS_NETADDR is False:
        log.error('Error: netaddr is not installed')
        # If we cannot check, assume all is ok
        return False

    cidr = config.get_cloud_config_value(
        'ignore_cidr', vm_, __opts__, default='', search_global=False
    )
    if cidr != '' and all_matching_cidrs(ip, [cidr]):
        log.warning(
            'IP {0!r} found within {1!r}; ignoring it.'.format(ip, cidr)
        )
        return True

    return False
github NVISO-BE / ee-outliers / app / helpers / utils.py View on Github external
def match_ip_ranges(source_ip, ip_cidr):
    """
    Check if an ip is in a specific range

    :param source_ip: ip to test
    :param ip_cidr: mask of ip to test
    :return: True if match, False otherwise
    """
    return False if len(netaddr.all_matching_cidrs(source_ip, ip_cidr)) <= 0 else True