def _ip_match()

in gcpdiag/queries/network.py [0:0]


def _ip_match(  #
    ip1: IPAddrOrNet,
    ip2_list: List[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]],
    match_type: str = 'allow') -> bool:
  """Match IP address or network to a network list (i.e. verify that ip1 is
  included in any ip of ip2_list).

  If match_type is 'allow', ip1 will match any ip in ip2_list if it is a subnet.
  If match_type is 'deny', ip1 will match any ip in ip2_list if they overlap
  (i.e. even if only part of ip1 is matched, it should still be considered a match)."""
  for ip2 in ip2_list:
    if isinstance(ip1, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
      # ip1: address, ip2: network
      if ip1 in ip2:
        return True
    else:
      # ip1: network, ip2: network
      if isinstance(ip1, ipaddress.IPv4Network) and \
          isinstance(ip2, ipaddress.IPv4Network):
        if match_type == 'allow' and ip1.subnet_of(ip2):
          return True
        elif match_type == 'deny' and ip1.overlaps(ip2):
          return True
        else:
          logging.debug('network no match %s of %s (%s matching)', ip1, ip2,
                        match_type)
      elif isinstance(ip1, ipaddress.IPv6Network) and \
          isinstance(ip2, ipaddress.IPv6Network):
        if match_type == 'allow' and ip1.subnet_of(ip2):
          return True
        elif match_type == 'deny' and ip1.overlaps(ip2):
          return True
  return False