How to use the netaddr.ip.IPAddress 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 / netaddr / ip / iana.py View on Github external
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 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 drkjam / netaddr / netaddr / ip / glob.py View on Github external
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)

    return IPAddress('.'.join(start_tokens)), IPAddress('.'.join(end_tokens))
github n0stack / n0stack / n0core / model / resource / network.py View on Github external
def apply_subnet(self,
                     cidr,         # type: str
                     range,        # type: str
                     nameservers,  # type: List[str]
                     gateway       # type: str
                     ):
        # type: (...) -> None
        for i, s in enumerate(self.subnets):
            if IPSet([cidr]) & IPSet(s.cidr):
                self.subnets.pop(i)

        ip_range = IPRange(range.split("-")[0], range.split("-")[1])
        ns = list(map(lambda n: IPAddress(n), nameservers))
        dhcp = _DHCP(ip_range, ns, IPAddress(gateway))
        subnet = _Subnet(IPNetwork(cidr), dhcp)

        self.__subnets.append(subnet)
github drkjam / netaddr / netaddr / ip / sets.py View on Github external
:param addr: An IP address or subnet, or an IPRange.

        :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:
github drkjam / netaddr / netaddr / ip / sets.py View on Github external
current_version, current_start, current_stop = sorted_ranges[0]

    for next_version, next_start, next_stop in sorted_ranges[1:]:
        if next_start == current_stop + 1 and next_version == current_version:
            # Can be merged.
            current_stop = next_stop
            continue
        # Cannot be merged.
        yield (IPAddress(current_start, current_version),
               IPAddress(current_stop, current_version))
        current_start = next_start
        current_stop = next_stop
        current_version = next_version
    yield (IPAddress(current_start, current_version),
           IPAddress(current_stop, current_version))
github drkjam / netaddr / lib3 / netaddr / ip / rfc1924.py View on Github external
def base85_to_ipv6(addr):
    """
    Convert a base 85 IPv6 address to its hexadecimal format.
    """
    tokens = list(addr)

    if len(tokens) != 20:
        raise AddrFormatError('Invalid base 85 IPv6 addess: %r' % addr)

    result = 0
    for i, num in enumerate(reversed(tokens)):
        num = BASE_85_DICT[num]
        result += (num * 85 ** i)

    ip = IPAddress(result, 6)

    return str(ip)
github crossbario / crossbar / v1 / crossbar / adminwebmodule / pgconnects.py View on Github external
def _checkSpec(self, spec, errs):

      errcnt = 0

      if not errs["host"] and spec.has_key("host"):
         host = str(spec["host"])
         try:
            addr = IPAddress(host)
            spec["host"] = str(addr)
         except Exception, e:
            errs["host"].append((self.proto.shrink(URI_ERROR + "invalid-attribute-value"),
                                 "Illegal value '%s' for host (%s)." % (host, str(e))))
            errcnt += 1

      return errcnt
github drkjam / netaddr / lib3 / netaddr / ip / sets.py View on Github external
r_ipv4_iset = _IntSet(*[(c.first, c.last) for c in r_ipv4])

        ipv4_result = l_ipv4_iset & r_ipv4_iset

        for start, end in list(ipv4_result._ranges):
            cidrs = iprange_to_cidrs(IPAddress(start, 4), IPAddress(end-1, 4))
            cidr_list.extend(cidrs)

        #   Process IPv6.
        l_ipv6_iset = _IntSet(*[(c.first, c.last) for c in l_ipv6])
        r_ipv6_iset = _IntSet(*[(c.first, c.last) for c in r_ipv6])

        ipv6_result = l_ipv6_iset & r_ipv6_iset

        for start, end in list(ipv6_result._ranges):
            cidrs = iprange_to_cidrs(IPAddress(start, 6), IPAddress(end-1, 6))
            cidr_list.extend(cidrs)

        return IPSet(cidr_list)