Python ipaddress.IPNetwork() Examples

The following are 3 code examples of ipaddress.IPNetwork(). 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: nacaddr.py    From capirca with Apache License 2.0 5 votes vote down vote up
def CollapseAddrListPreserveTokens(addresses):
  """Collapse an array of IPs only when their tokens are the same.

  Args:
     addresses: list of ipaddress.IPNetwork objects.

  Returns:
    list of ipaddress.IPNetwork objects.
  """
  ret_array = []
  for grp in itertools.groupby(sorted(addresses, key=lambda x: x.parent_token),
                               lambda x: x.parent_token):
    ret_array.append(CollapseAddrList(list(grp[1])))
  dedup_array = []
  i = 0
  while len(ret_array) > i:
    ip = ret_array.pop(0)
    k = 0
    to_add = True
    while k < len(dedup_array):
      if IsSuperNet(dedup_array[k], ip):
        to_add = False
        break
      elif IsSuperNet(ip, dedup_array[k]):
        del dedup_array[k]
      k += 1
    if to_add:
      dedup_array.append(ip)
  return [i for sublist in dedup_array for i in sublist] 
Example #2
Source File: nacaddr.py    From capirca with Apache License 2.0 5 votes vote down vote up
def CollapseAddrList(addresses, complement_addresses=None):
  """Collapse an array of IP objects.

  Example:  CollapseAddrList(
    [IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) -> [IPv4('1.1.0.0/23')]
    Note: this works just as well with IPv6 addresses too.

  On platforms that support exclude semantics with most specific match,
  this method should _always_ be called with complement addresses supplied.
  Not doing so can lead to *reversal* of intent. Consider this case:

    destination-address:: 10.0.0.0/8, 10.0.0.0/10
    destination-exclude:: 10.0.0.0/9

  Without optimization, 10.0.0.1 will _match_. With optimization, most specific
  prefix will _not_ match, reversing the intent. Supplying complement_addresses
  allows this method to consider those implications.

  Args:
     addresses: list of ipaddress.IPNetwork objects
     complement_addresses: list of ipaddress.IPNetwork objects that, if present,
      will be considered to avoid harmful optimizations.

  Returns:
    list of ipaddress.IPNetwork objects
  """
  complements_dict = collections.defaultdict(list)
  address_set = set([a.network_address for a in addresses])
  for ca in complement_addresses or []:
    if ca.network_address in address_set:
      complements_dict[ca.network_address].append(ca)
  return _CollapseAddrListInternal(
      sorted(addresses, key=ipaddress.get_mixed_type_key), complements_dict) 
Example #3
Source File: spf.py    From mailin with MIT License 4 votes vote down vote up
def cidrmatch(self, ipaddrs, n):
        """Match connect IP against a CIDR network of other IP addresses.

        Examples:
        >>> c = query(s='strong-bad@email.example.com',
        ...           h='mx.example.org', i='192.0.2.3')
        >>> c.p = 'mx.example.org'
        >>> c.r = 'example.com'

        >>> c.cidrmatch(['192.0.2.3'],32)
        True
        >>> c.cidrmatch(['192.0.2.2'],32)
        False
        >>> c.cidrmatch(['192.0.2.2'],31)
        True

        >>> six = query(s='strong-bad@email.example.com',
        ...           h='mx.example.org', i='2001:0db8:0:0:0:0:0:0001')
        >>> six.p = 'mx.example.org'
        >>> six.r = 'example.com'

        >>> six.cidrmatch(['2001:0DB8::'],127)
        True
        >>> six.cidrmatch(['2001:0DB8::'],128)
        False
        >>> six.cidrmatch(['2001:0DB8:0:0:0:0:0:0001'],128)
        True
        """
        try:
            for netwrk in [ipaddress.ip_network(ip) for ip in ipaddrs]:
                network = netwrk.supernet(new_prefix=n)
                if isinstance(self.iplist, bool):
                    if network.__contains__(self.ipaddr):
                        return True
                else:
                    if n < self.cidrmax:
                        self.iplist.append(network)
                    else:
                        self.iplist.append(network.ip)
        except AttributeError:
            for netwrk in [ipaddress.IPNetwork(ip,strict=False) for ip in ipaddrs]:
                network = netwrk.supernet(new_prefix=n)
                if isinstance(self.iplist, bool):
                    if network.__contains__(self.ipaddr):
                        return True
                else:
                    if n < self.cidrmax:
                        self.iplist.append(network)
                    else:
                        self.iplist.append(network.ip)
        return False