Python ipaddress.IPv6Network() Examples

The following are 30 code examples of ipaddress.IPv6Network(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipaddress , or try the search function .
Example #1
Source File: general_name.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #2
Source File: networking.py    From deckard with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self,
                 interface="deckard",
                 ip4_range=IPv4Network('127.127.0.0/16'),
                 ip6_range=IPv6Network('fd00:dec::/32')):
        self.ip4_internal_range = ip4_range
        self.ip6_internal_range = ip6_range
        self.ip4_iterator = (host for host in ip4_range)
        self.ip6_iterator = (host for host in ip6_range)
        self.added_addresses = set()
        self.interface = interface

        self._ip = IPRoute()
        try:
            self._dev = self._setup_interface()
        except NetlinkError:
            raise RuntimeError(f"Couldn't set interface `{self.interface}` up.") 
Example #3
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #4
Source File: general_name.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #5
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #6
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def testGetSubnets3(self):
        subnets = [str(x) for x in self.ipv4_network.subnets(8)]
        self.assertEqual(subnets[:3],
            ['1.2.3.0/32', '1.2.3.1/32', '1.2.3.2/32'])
        self.assertEqual(subnets[-3:],
            ['1.2.3.253/32', '1.2.3.254/32', '1.2.3.255/32'])
        self.assertEqual(len(subnets), 256)

        ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/120')
        subnets = [str(x) for x in ipv6_network.subnets(8)]
        self.assertEqual(subnets[:3],
            ['2001:658:22a:cafe::/128',
             '2001:658:22a:cafe::1/128',
             '2001:658:22a:cafe::2/128'])
        self.assertEqual(subnets[-3:],
            ['2001:658:22a:cafe::fd/128',
             '2001:658:22a:cafe::fe/128',
             '2001:658:22a:cafe::ff/128'])
        self.assertEqual(len(subnets), 256) 
Example #7
Source File: general_name.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #8
Source File: conf.py    From faucet with Apache License 2.0 6 votes vote down vote up
def _str_conf(self, conf_v):
        if isinstance(conf_v, (bool, str, int)):
            return conf_v
        if isinstance(conf_v, (
                ipaddress.IPv4Address, ipaddress.IPv4Interface, ipaddress.IPv4Network,
                ipaddress.IPv6Address, ipaddress.IPv6Interface, ipaddress.IPv6Network)):
            return str(conf_v)
        if isinstance(conf_v, (dict, OrderedDict)):
            return {str(i): self._str_conf(j) for i, j in conf_v.items() if j is not None}
        if isinstance(conf_v, (list, tuple, frozenset)):
            return tuple([self._str_conf(i) for i in conf_v if i is not None])
        if isinstance(conf_v, Conf):
            for i in ('name', '_id'):
                if hasattr(conf_v, i):
                    return getattr(conf_v, i)
        return None 
Example #9
Source File: general_name.py    From oss-ftp with MIT License 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #10
Source File: roa.py    From NeoNetwork with The Unlicense 6 votes vote down vote up
def prehandle_roa(asn_table: dict, args):
    roa = route_to_roa(asn_table)
    max_prefixlen = IPv4Network(0).max_prefixlen
    roa4 = filter(lambda item: isinstance(item["prefix"], IPv4Network), roa)
    roa6 = filter(lambda item: isinstance(item["prefix"], IPv6Network), roa)
    if args.ipv4:
        roa6 = []
    elif args.ipv6:
        roa4 = []
    roa4 = [
        r
        for r in roa4
        if r["prefix"].prefixlen <= args.max or r["prefix"].prefixlen == max_prefixlen
    ]
    roa6 = [r for r in roa6 if r["prefix"].prefixlen <= args.max6]
    for r in roa4:
        r["maxLength"] = args.max
        if r["prefix"].prefixlen == max_prefixlen:
            r["maxLength"] = max_prefixlen
    for r in roa6:
        r["maxLength"] = args.max6
    for r in (*roa4, *roa6):
        r["prefix"] = r["prefix"].with_prefixlen
    return roa4, roa6 
Example #11
Source File: __init__.py    From py-mmdb-encoder with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def insert_network(self, prefix, data_offset, strict = True):
        self.entries_count += 1
        ipnet = ipaddress.ip_network(prefix, strict=False)

        if ipnet.version == 6 and self.ip_version != 6:
            raise Exception('Encoder: insert_network: cannot add IPv6 address in IPv4 table')

        if ipnet.version == 4 and self.ip_version == 6:
            base4in6 = ipaddress.IPv6Address(u'::ffff:0:0')
            v4in6addr = ipaddress.IPv6Address(int(ipnet.network_address)+int(base4in6))

            # Maxmind DBs skips the first 96 bits (do not include the 0xffff)
            if self.compat:
                v4in6addr = ipaddress.IPv6Address(int(ipnet.network_address))

            v4in6addr_plen = ipnet.prefixlen + 96
            ipnet = ipaddress.IPv6Network(u'{}/{}'.format(str(v4in6addr), v4in6addr_plen), strict=False)

        #print(ipnet)
        self.add_to_trie(ipnet, data_offset, strict=strict) 
Example #12
Source File: common.py    From VxWireguard-Generator with MIT License 6 votes vote down vote up
def generate_pubkey_ipv6(network: Config.NetworkType, node: Config.NodeType) -> Optional[str]:
    if 'AddressPoolIPv6' not in network:
        return None
    address_pool = ipaddress.IPv6Network(network['AddressPoolIPv6'], strict=False)

    if 'PrivateKey' not in node:
        return None
    secret_base64: str = node['PrivateKey']
    secret: bytes = binascii.a2b_base64(secret_base64)
    if len(secret) != 32:
        return None

    host = ipaddress.IPv6Address(pubkey(secret)[-16:])
    ipv6 = ipaddress.IPv6Address(int(address_pool.network_address) | (int(host) & int(address_pool.hostmask)))

    return ipv6.compressed + '/' + str(address_pool.prefixlen) 
Example #13
Source File: general_name.py    From quickstart-redhat-openshift with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #14
Source File: nacaddr.py    From capirca with Apache License 2.0 6 votes vote down vote up
def supernet(self, prefixlen_diff=1):
    """Override ipaddress.IPv6Network supernet so we can maintain comments.

    See ipaddress.IPv6Network.Supernet for complete documentation.
    Args:
      prefixlen_diff: Prefix length difference.

    Returns:
      An IPv4 object

    Raises:
      PrefixlenDiffInvalidError: Raised when prefixlen - prefixlen_diff results
        in a negative number.
    """
    if self.prefixlen == 0:
      return self
    if self.prefixlen - prefixlen_diff < 0:
      raise PrefixlenDiffInvalidError(
          'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (
              self.prefixlen, prefixlen_diff))
    ret_addr = IPv6(ipaddress.IPv6Network.supernet(self, prefixlen_diff),
                    comment=self.text, token=self.token)
    return ret_addr

  # Backwards compatibility name from v1. 
Example #15
Source File: general_name.py    From quickstart-git2s3 with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #16
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def network(self):
        """Returns an IPv6Network object, which represents this network.
        """
        if sys.version_info[0] < 3:
            return self.network_object.network
        else:
            ## The ipaddress module returns an "IPAddress" object in Python3...
            return IPv6Network("{0}".format(self.network_object.compressed)) 
Example #17
Source File: cisco.py    From capirca with Apache License 2.0 5 votes vote down vote up
def _GetIpString(self, addr):
    """Formats the address object for printing in the ACL.

    Args:
      addr: str or ipaddr, address
    Returns:
      An address string suitable for the ACL.
    """
    if isinstance(addr, nacaddr.IPv4) or isinstance(addr,
                                                    ipaddress.IPv4Network):
      addr = cast(self.IPV4_ADDRESS, addr)
      if addr.num_addresses > 1:
        if self.platform == 'arista':
          return addr.with_prefixlen
        return '%s %s' % (addr.network_address, addr.hostmask)
      return 'host %s' % (addr.network_address)
    if isinstance(addr, nacaddr.IPv6) or isinstance(addr,
                                                    ipaddress.IPv6Network):
      addr = cast(self.IPV6_ADDRESS, addr)
      if addr.num_addresses > 1:
        return addr.with_prefixlen
      return 'host %s' % (addr.network_address)
    # DSMO enabled
    if isinstance(addr, summarizer.DSMNet):
      return '%s %s' % summarizer.ToDottedQuad(addr, negate=True)
    return addr 
Example #18
Source File: valve_of.py    From faucet with Apache License 2.0 5 votes vote down vote up
def _match_ip_masked(ipa):
    if isinstance(ipa, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
        return (str(ipa.network_address), str(ipa.netmask))
    return (str(ipa.ip), str(ipa.netmask)) 
Example #19
Source File: extensions.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            ) 
Example #20
Source File: ip.py    From ttp with MIT License 5 votes vote down vote up
def to_net(data, *args):
    # for py2 support need to convert data to unicode:
    if _ttp_["python_major_version"] is 2:
        ipaddr_data = unicode(data)
    elif _ttp_["python_major_version"] is 3:
        ipaddr_data = data
    if "ipv4" in args:
        return ipaddress.IPv4Network(ipaddr_data), None
    elif "ipv6" in args:
        return ipaddress.IPv6Network(ipaddr_data), None
    else:
        return ipaddress.ip_network(ipaddr_data), None 
Example #21
Source File: extensions.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            ) 
Example #22
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def prefixlen(self, arg):
        """prefixlen setter method"""
        self.network_object = IPv6Network(
            "{0}/{1}".format(str(self.ip_object), arg), strict=False
        ) 
Example #23
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, arg="::1/128", strict=False):

        # arg= _RGX_IPV6ADDR_NETMASK.sub(r'\1/\2', arg) # mangle IOS: 'addr mask'
        self.arg = arg
        self.dna = "IPv6Obj"

        try:
            mm = _RGX_IPV6ADDR.search(arg)
        except TypeError:
            if getattr(arg, "dna", "") == "IPv6Obj":
                ip_str = "{0}/{1}".format(str(arg.ip_object), arg.prefixlen)
                self.network_object = IPv6Network(ip_str, strict=False)
                self.ip_object = IPv6Address(str(arg.ip_object))
                return None
            elif isinstance(arg, IPv6Network):
                self.network_object = arg
                self.ip_object = IPv6Address(str(arg).split("/")[0])
                return None
            elif isinstance(arg, IPv6Address):
                self.network_object = IPv6Network(str(arg) + "/128")
                self.ip_object = IPv6Address(str(arg).split("/")[0])
                return None
            elif isinstance(arg, int):
                self.ip_object = IPv6Address(arg)
                self.network_object = IPv6Network(
                    str(self.ip_object) + "/128", strict=False
                )
                return None
            else:
                raise ValueError(
                    "IPv6Obj doesn't understand how to parse {0}".format(arg)
                )

        assert not (mm is None), "IPv6Obj couldn't parse {0}".format(arg)
        self.network_object = IPv6Network(arg, strict=strict)
        self.ip_object = IPv6Address(mm.group(1))

    # 'address_exclude', 'compare_networks', 'hostmask', 'ipv4_mapped', 'iter_subnets', 'iterhosts', 'masked', 'max_prefixlen', 'netmask', 'network', 'numhosts', 'overlaps', 'prefixlen', 'sixtofour', 'subnet', 'supernet', 'teredo', 'with_hostmask', 'with_netmask', 'with_prefixlen' 
Example #24
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def is_reserved(self):
        """Returns a boolean for whether this is a reserved address"""
        return self.network_object.is_reserved


## Emulate the old behavior of ipaddr.IPv6Network in Python2, which can use
##    IPv6Network with a host address.  Google removed that in Python3's
##    ipaddress.py module 
Example #25
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testForceVersion(self):
        self.assertEqual(ipaddress.ip_network(1).version, 4)
        self.assertEqual(ipaddress.IPv6Network(1).version, 6) 
Example #26
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testExplodeShortHandIpStr(self):
        addr1 = ipaddress.IPv6Interface('2001::1')
        addr2 = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
        addr3 = ipaddress.IPv6Network('2001::/96')
        addr4 = ipaddress.IPv4Address('192.168.178.1')
        self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001/128',
                         addr1.exploded)
        self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128',
                         ipaddress.IPv6Interface('::1/128').exploded)
        # issue 77
        self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
                         addr2.exploded)
        self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0000/96',
                         addr3.exploded)
        self.assertEqual('192.168.178.1', addr4.exploded) 
Example #27
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testGetSubnetForSingle128(self):
        ip = ipaddress.IPv6Network('::1/128')
        subnets1 = [str(x) for x in ip.subnets()]
        subnets2 = [str(x) for x in ip.subnets(2)]
        self.assertEqual(subnets1, ['::1/128'])
        self.assertEqual(subnets1, subnets2) 
Example #28
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testGetSupernet(self):
        self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
        self.assertEqual(str(self.ipv4_network.supernet().network_address),
                         '1.2.2.0')
        self.assertEqual(
            ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
            ipaddress.IPv4Network('0.0.0.0/0'))

        self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
        self.assertEqual(str(self.ipv6_network.supernet().network_address),
                         '2001:658:22a:cafe::')
        self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
                         ipaddress.IPv6Network('::0/0')) 
Example #29
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
        self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
        self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
        #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
        self.ipv6_address = ipaddress.IPv6Interface(
            '2001:658:22a:cafe:200:0:0:1')
        self.ipv6_interface = ipaddress.IPv6Interface(
            '2001:658:22a:cafe:200:0:0:1/64')
        self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64') 
Example #30
Source File: extensions.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )