How to use the netaddr.core.AddrFormatError 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 napalm-automation / napalm / test / base / test_helpers.py View on Github external
def test_ip(self):
        """
        Tests the helper function ```ip```:

            * check if raises AddrFormatError when invalid IP address
            * check if calls using incorrect version raises ValueError
            * check if IPv6 address returned as expected
        """

        self.assertTrue(HAS_NETADDR)

        # test that raises AddrFormatError when wrong format
        self.assertRaises(AddrFormatError, napalm.base.helpers.ip, "fake")
        self.assertRaises(
            ValueError,
            napalm.base.helpers.ip,
            "2001:db8:85a3::8a2e:370:7334",
            version=4,
        )
        self.assertRaises(ValueError, napalm.base.helpers.ip, "192.168.17.1", version=6)
        self.assertEqual(
            napalm.base.helpers.ip("2001:0dB8:85a3:0000:0000:8A2e:0370:7334"),
            "2001:db8:85a3::8a2e:370:7334",
        )
        self.assertEqual(
            napalm.base.helpers.ip("2001:0DB8::0003", version=6), "2001:db8::3"
        )
github drkjam / netaddr / netaddr / ip / glob.py View on Github external
def glob_to_iptuple(ipglob):
    """
    A function that accepts a glob-style IP range and returns the component
    lower and upper bound IP address.

    :param ipglob: an IP address range in a glob-style format.

    :return: a tuple contain lower and upper bound IP objects.
    """
    if not valid_glob(ipglob):
        raise AddrFormatError('not a recognised IP glob range: %r!' % ipglob)

    start_tokens = []
    end_tokens = []

    for octet in ipglob.split('.'):
        if '-' in octet:
            tokens = octet.split('-')
            start_tokens.append(tokens[0])
            end_tokens.append(tokens[1])
        elif octet == '*':
            start_tokens.append('0')
            end_tokens.append('255')
        else:
            start_tokens.append(octet)
            end_tokens.append(octet)
github drkjam / netaddr / netaddr / ip / nmap.py View on Github external
def _parse_nmap_target_spec(target_spec):
    if '/' in target_spec:
        _, prefix = target_spec.split('/', 1)
        if not (0 < int(prefix) < 33):
            raise AddrFormatError('CIDR prefix expected, not %s' % prefix)
        net = IPNetwork(target_spec)
        if net.version != 4:
            raise AddrFormatError('CIDR only support for IPv4!')
        for ip in net:
            yield ip
    elif ':' in target_spec:
        #   nmap only currently supports IPv6 addresses without prefixes.
        yield IPAddress(target_spec)
    else:
        octet_ranges = _generate_nmap_octet_ranges(target_spec)
        for w in octet_ranges[0]:
            for x in octet_ranges[1]:
                for y in octet_ranges[2]:
                    for z in octet_ranges[3]:
                        yield IPAddress("%d.%d.%d.%d" % (w, x, y, z), 4)
github shupp / VegaDNS-API / vegadns / ip.py View on Github external
def uncompress(self, ip):
        try:
            ip = netaddr.IPAddress(ip)
            return ip.format(netaddr.ipv6_verbose)
        except netaddr.core.AddrFormatError:
            raise IPException('Invalid IPv6 address: ' + ip)
github CiscoDevNet / devnet-express-code-samples / LM-4602 / create_subinterface.py View on Github external
help="password on remote host")
    parser.add_argument('--port', '-P', default=PORT,
                        help="port on remote host")
    parser.add_argument('--host', '-H', default=HOST, help="remote host")
    args = parser.parse_args()

    # check for valid VLAN ID
    if args.vlan < 1 or args.vlan > 4094:
        parser.print_usage()
        print("invalid VLAN ID %s" % str(args.vlan))
        return -1

    # check for valid prefix
    try:
        ip = netaddr.IPNetwork(args.prefix)
    except netaddr.core.AddrFormatError as e:
        parser.print_usage()
        print(e)
        return -1

    # insecure?
    if args.ssl and args.insecure:
        requests.packages.urllib3.disable_warnings()

    return create_vlan(args.host, args.port, args.user,
                       args.password, args.interface,
                       args.vlan, ip, args.ssl, args.insecure)
github saltstack / salt / salt / runners / net.py View on Github external
def _get_network_obj(addr):
    '''
    Try to convert a string into a valid IP Network object.
    '''
    ip_netw = None
    try:
        ip_netw = IPNetwork(addr)
    except AddrFormatError:
        return ip_netw
    return ip_netw
github openstack / neutron / neutron / services / vpn / service_drivers / ipsec.py View on Github external
def _make_vpnservice_dict(self, vpnservice):
        """Convert vpnservice information for vpn agent.

        also converting parameter name for vpn agent driver
        """
        vpnservice_dict = dict(vpnservice)
        vpnservice_dict['ipsec_site_connections'] = []
        vpnservice_dict['subnet'] = dict(
            vpnservice.subnet)
        vpnservice_dict['external_ip'] = vpnservice.router.gw_port[
            'fixed_ips'][0]['ip_address']
        for ipsec_site_connection in vpnservice.ipsec_site_connections:
            ipsec_site_connection_dict = dict(ipsec_site_connection)
            try:
                netaddr.IPAddress(ipsec_site_connection['peer_id'])
            except netaddr.core.AddrFormatError:
                ipsec_site_connection['peer_id'] = (
                    '@' + ipsec_site_connection['peer_id'])
            ipsec_site_connection_dict['ikepolicy'] = dict(
                ipsec_site_connection.ikepolicy)
            ipsec_site_connection_dict['ipsecpolicy'] = dict(
                ipsec_site_connection.ipsecpolicy)
            vpnservice_dict['ipsec_site_connections'].append(
                ipsec_site_connection_dict)
            peer_cidrs = [
                peer_cidr.cidr
                for peer_cidr in ipsec_site_connection.peer_cidrs]
            ipsec_site_connection_dict['peer_cidrs'] = peer_cidrs
        return vpnservice_dict
github openstack / networking-bagpipe / networking_bagpipe / driver / sfc.py View on Github external
def _parse_ipaddress_prefix(self, cidr):
        try:
            net = IPNetwork(cidr)
            return (str(net.ip), net.prefixlen)
        except AddrFormatError:
            raise exc.SfcDriverError(message=(
                "Malformed IP prefix: %s" % cidr))
github projectcalico / libcalico / calico_containers / pycalico / util.py View on Github external
def verify_cidr(cidr):
    """
    Validate cidr is in correct CIDR notation

    :param cidr: IP addr and associated routing prefix
    :type cidr: str
    :return: None
    :rtype: None
    """
    try:
        netaddr.IPNetwork(cidr)
    except (AddrFormatError, ValueError) as exc:
        # Some versions of Netaddr have a bug causing them to return a
        # ValueError rather than an AddrFormatError, so catch both.
        raise AddrValidationError("CIDR is invalid. " + str(exc).capitalize())
github datacenter / ignite-DEPRECATED / autonetkit / design / igp.py View on Github external
default_area = area_zero_int
    if any(router.area == "0.0.0.0" for router in g_ospf):
        # string comparison as hasn't yet been cast to IPAddress
        default_area = area_zero_ip

    for router in g_ospf:
        if not router.area or router.area == "None":
            router.area = default_area
            # check if 0.0.0.0 used anywhere, if so then use 0.0.0.0 as format
        else:
            try:
                router.area = int(router.area)
            except ValueError:
                try:
                    router.area = netaddr.IPAddress(router.area)
                except netaddr.core.AddrFormatError:
                    router.log.warning("Invalid OSPF area %s. Using default"
                                       " of %s" % (router.area, default_area))
                    router.area = default_area

    # TODO: use interfaces throughout, rather than edges
    for router in g_ospf:
        # and set area on interface
        for edge in router.edges():
            if edge.area:
                continue  # allocated (from other "direction", as undirected)
            if router.area == edge.dst.area:
                edge.area = router.area  # intra-area
                continue

            if router.area in area_zero_ids or edge.dst.area in area_zero_ids:
                # backbone to other area