How to use the netaddr.ip.IPNetwork 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 / lib3 / netaddr / ip / iana.py View on Github external
def update(self, data):
        """
        Callback function used by Publisher to notify this Subscriber about
        an update. Stores topic based information into dictionary passed to
        constructor.
        """
        data_id = data[self.unique_key]

        if self.topic == 'IPv4':
            cidr = IPNetwork(cidr_abbrev_to_verbose(data_id))
            self.dct[cidr] = data
        elif self.topic == 'IPv6':
            cidr = IPNetwork(cidr_abbrev_to_verbose(data_id))
            self.dct[cidr] = data
        elif self.topic == 'multicast':
            iprange = None
            if '-' in data_id:
                #   See if we can manage a single CIDR.
                (first, last) = data_id.split('-')
                iprange = IPRange(first, last)
                cidrs = iprange.cidrs()
                if len(cidrs) == 1:
                    iprange = cidrs[0]
            else:
                iprange = IPAddress(data_id)
            self.dct[iprange] = data
github drkjam / netaddr / netaddr / ip / iana.py View on Github external
def update(self, data):
        """
        Callback function used by Publisher to notify this Subscriber about
        an update. Stores topic based information into dictionary passed to
        constructor.
        """
        data_id = data[self.unique_key]

        if self.topic == 'IPv4':
            cidr = IPNetwork(cidr_abbrev_to_verbose(data_id))
            self.dct[cidr] = data
        elif self.topic == 'IPv6':
            cidr = IPNetwork(cidr_abbrev_to_verbose(data_id))
            self.dct[cidr] = data
        elif self.topic == 'IPv6_unicast':
            cidr = IPNetwork(data_id)
            self.dct[cidr] = data
        elif self.topic == 'multicast':
            iprange = None
            if '-' in data_id:
                #   See if we can manage a single CIDR.
                (first, last) = data_id.split('-')
                iprange = IPRange(first, last)
                cidrs = iprange.cidrs()
                if len(cidrs) == 1:
                    iprange = cidrs[0]
            else:
                iprange = IPAddress(data_id)
            self.dct[iprange] = data
github NLnetLabs / ldns / cga-gen / cga-gen.py View on Github external
print("Invalid modifier encoding.")
			exit()

	if pfx == None:
		try:
			a = ni.ifaddresses('eth0')[10][0]['addr']
		except KeyError:
			print("Could not get prefix: no IPv6 address found at 'eth0'; alternatively pass a prefix in command line argument.")
			exit()
		try:
			m = ni.ifaddresses('eth0')[10][0]['netmask']
		except KeyError:
			print("Could not get prefix: no subnet mask found at 'eth0'; alternatively pass a prefix in command line argument.")
			exit()

		pfx = str(IPAddress(int(IPNetwork(a).network) & int(IPNetwork(m).network)))
	else:
		if pfx[-1] != ':':
			pfx = pfx + ':'
		if len(pfx) < 2 or pfx[-2] != ':':
			pfx = pfx + ':'

	try:
		pk = PubKey(pk)
	except:
		print("Could not import public key. Wrong format?")
		exit()

	# generate CGA
	try:
		(addr, params) = CGAgen(pfx, pk, sec, ext, dad, mod, col)
	except socket.error, v:
github drkjam / netaddr / netaddr / ip / sets.py View on Github external
:param flags: decides which rules are applied to the interpretation
            of the addr value. See the netaddr.core namespace documentation
            for supported constant values.

        """
        if isinstance(addr, IPRange):
            new_cidrs = dict.fromkeys(
                iprange_to_cidrs(addr[0], addr[-1]), True)
            self._cidrs.update(new_cidrs)
            self.compact()
            return
        if isinstance(addr, IPNetwork):
            # Networks like 10.1.2.3/8 need to be normalized to 10.0.0.0/8
            addr = addr.cidr
        elif isinstance(addr, _int_type):
            addr = IPNetwork(IPAddress(addr, flags=flags))
        else:
            addr = IPNetwork(addr)

        self._cidrs[addr] = True
        self._compact_single_network(addr)
github drkjam / netaddr / netaddr / ip / sets.py View on Github external
:param flags: decides which rules are applied to the interpretation
            of the addr value. See the netaddr.core namespace documentation
            for supported constant values.

        """
        if isinstance(addr, IPRange):
            cidrs = iprange_to_cidrs(addr[0], addr[-1])
            for cidr in cidrs:
                self.remove(cidr)
            return

        if isinstance(addr, _int_type):
            addr = IPAddress(addr, flags=flags)
        else:
            addr = IPNetwork(addr)

        #   This add() is required for address blocks provided that are larger
        #   than blocks found within the set but have overlaps. e.g. :-
        #
        #   >>> IPSet(['192.0.2.0/24']).remove('192.0.2.0/23')
        #   IPSet([])
        #
        self.add(addr)

        remainder = None
        matching_cidr = None

        #   Search for a matching CIDR and exclude IP from it.
        for cidr in self._cidrs:
            if addr in cidr:
                remainder = cidr_exclude(cidr, addr)
github internap / netman / netman / adapters / switches / cisco.py View on Github external
def apply_interface_running_config_data(vlan, data):
    for line in data:
        if regex.match("^ ip address ([^\s]*) ([^\s]*)(.*)", line):
            ip = IPNetwork("{}/{}".format(regex[0], regex[1]))
            if "secondary" not in regex[2]:
                vlan.ips.insert(0, ip)
            else:
                vlan.ips.append(ip)

        elif regex.match("^ ip access-group ([^\s]*) ([^\s]*).*", line):
            if regex[1] == "in":
                vlan.access_groups[IN] = regex[0]
            else:
                vlan.access_groups[OUT] = regex[0]

        elif regex.match("^ ip vrf forwarding ([^\s]*).*", line):
            vlan.vrf_forwarding = regex[0]

        elif regex.match("^ standby ([\d]+) (.*)", line):
            vrrp_group = next((group for group in vlan.vrrp_groups if str(group.id) == regex[0]), None)
github cobbler / cobbler / cobbler / utils.py View on Github external
def get_host_ip(ip, shorten=True):
    """
    Return the IP encoding needed for the TFTP boot tree.
    """
    cidr = None

    if NETADDR_PRE_0_7:
        ip = netaddr.IP(ip)
        cidr = ip.cidr()
    else:
        ip = netaddr.ip.IPAddress(ip)
        cidr = netaddr.ip.IPNetwork(ip)

    if len(cidr) == 1: # Just an IP, e.g. a /32
        return pretty_hex(ip)
    else:
        pretty = pretty_hex(cidr[0])
        if not shorten or len(cidr) <= 8:
            # not enough to make the last nibble insignificant
            return pretty
        else:
            cutoff = (32 - cidr.prefixlen) / 4
            return pretty[0:-cutoff]
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 drkjam / netaddr / netaddr / ip / sets.py View on Github external
def __contains__(self, ip):
        """
        :param ip: An IP address or subnet.

        :return: ``True`` if IP address or subnet is a member of this IP set.
        """
        # Iterating over self._cidrs is an O(n) operation: 1000 items in
        # self._cidrs would mean 1000 loops. Iterating over all possible
        # supernets loops at most 32 times for IPv4 or 128 times for IPv6,
        # no matter how many CIDRs this object contains.
        supernet = IPNetwork(ip)
        if supernet in self._cidrs:
            return True
        while supernet._prefixlen:
            supernet._prefixlen -= 1
            if supernet in self._cidrs:
                return True
        return False