Parse and validate forwarded IP addresses.

    Args:
      forwarded_ips: list, the IP address strings to parse.

    Returns:
      list, the valid IP address strings.
425376
def ParseForwardedIps(self, forwarded_ips):
    
    addresses = []
    forwarded_ips = forwarded_ips or []
    for ip in forwarded_ips:
      if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)):
        addresses.append(ip[:-3] if ip.endswith('/32') else ip)
      else:
        self.logger.warning('Could not parse IP address: "%s".', ip)
    return addresses
953110
def query(self, ip_address):
        
        try:
            return self._decode_response(
                socket.gethostbyname(self._build_query(ip_address)))
        except socket.gaierror:  # Not listed
            return {
                'days_since_last_activity': None,
                'name': None,
                'threat_score': 0,
                'type': None
            }
346197
def is_valid_ip_pattern(ip):
    """"""
    ip = ip.replace('*', '1')
    try:
        socket.inet_aton(ip)
        return True
    except socket.error:
        # Not a valid IPv4 address pattern
        return False
6448
def list_forwarding_addresses(api_key, offset=None, coin_symbol='btc'):
    '''
    
    '''

    assert is_valid_coin_symbol(coin_symbol)
    assert api_key

    url = make_url(coin_symbol, 'payments')

    params = {'token': api_key}

    if offset:
        params['start'] = offset

    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
1003773
def lookup_forward(name):
    """"""
    ip_addresses = {}

    addresses = list(set(str(ip[4][0]) for ip in socket.getaddrinfo(
        name, None)))

    if addresses is None:
        return ip_addresses

    for address in addresses:
        if type(ipaddress.ip_address(address)) is ipaddress.IPv4Address:
            ip_addresses['ipv4'] = address
        if type(ipaddress.ip_address(address)) is ipaddress.IPv6Address:
            ip_addresses['ipv6'] = address

    return ip_addresses
1057274
protected function extractForFromForwardedHeader($forwarded)
    {
        $ips = [];
        $parts = array_map('trim', explode(',', $forwarded));
        
        foreach ($parts as $part) {
            list($key, $value) = explode('=', $part, 2) + [1 => null];
            
            if ($key === 'for') {
                $ips[] = trim($value, '[]');
            }
        }
        
        return $ips;
    }
1103584
def ip_address_list(ips):
    
    # first, try it as a single IP address
    try:
        return ip_address(ips)
    except ValueError:
        pass
    # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it
    return list(ipaddress.ip_network(u(ips)).hosts())
220383
def parse_ip4(ip_output)
      cidr_ip = parse_ip_output(ip_output, /inet /, 1)
      return unless cidr_ip

      parts = cidr_ip.split('/')
      @network_conf[:address] = parts[0]
      @network_conf[:prefix] = parts[1].to_i
    end
1206342
def list_port_forwarding_rules(ip_address_id=nil, listall=false)
      params = { 'command' => 'listPortForwardingRules' }
      params['ipAddressId'] = ip_address_id if ip_address_id
      params['listall'] = listall
      json = send_request(params)
      json['portforwardingrule']
    end
1061668
def _parse_forward(mapping):
    '''
    
    '''
    if len(mapping.split(':')) > 3:
        (srcport, destport, protocol, destaddr) = mapping.split(':')
    else:
        (srcport, destport, protocol) = mapping.split(':')
        destaddr = ''
    return ForwardingMapping(srcport, destport, protocol, destaddr)
1113123
def _AddForwardedIps(self, forwarded_ips, interface):
    
    for address in forwarded_ips:
      self.ip_forwarding_utils.AddForwardedIp(address, interface)
1001353
def get_ip_address(request):
    
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
    else:
        return request.META['REMOTE_ADDR']
597085
def _parse_ip(addr):
    

    # Parse the IP address
    try:
        address = netaddr.IPAddress(addr.strip())
    except (ValueError, netaddr.AddrFormatError):
        return None

    # Canonicalize it, if possible
    if address.version == 6:
        try:
            return address.ipv4()
        except netaddr.AddrConversionError:
            pass

    return address
1128315
def ip_addresses(self):
        
        if self._ip_addresses is None:
            self._ip_addresses = IpAddressList(
                self._version,
                account_sid=self._solution['account_sid'],
                ip_access_control_list_sid=self._solution['sid'],
            )
        return self._ip_addresses
1333513
def _read_routes_c_v1():
    """"""
    def _extract_ip(obj):
        return inet_ntop(socket.AF_INET, struct.pack("<I", obj))
    routes = []
    for route in GetIpForwardTable():
        ifIndex = route['ForwardIfIndex']
        dest = route['ForwardDest']
        netmask = route['ForwardMask']
        nexthop = _extract_ip(route['ForwardNextHop'])
        metric = route['ForwardMetric1']
        # Build route
        try:
            iface = dev_from_index(ifIndex)
            if iface.ip == "0.0.0.0":
                continue
        except ValueError:
            continue
        ip = iface.ip
        # RouteMetric + InterfaceMetric
        metric = metric + iface.ipv4_metric
        routes.append((dest, netmask, nexthop, iface, ip, metric))
    return routes
583107
def parse_rules(content=None):
    
    rules = content.split(DELIMITER)
    parsed_rules = list()
    order = 1
    for rule in rules:
        if rule.strip() == '':
            continue
        parsed_rule = {}
        lines = rule.split("\n")
        parsed_rule['orderValue'] = order
        order += 1
        for line in lines:
            if line.strip() == '':
                continue
            key_value = line.strip().split(':')
            key = key_value[0].strip()
            value = key_value[1].strip()
            if key == 'action':
                parsed_rule['action'] = value
            elif key == 'protocol':
                parsed_rule['protocol'] = value
            elif key == 'source_ip_address':
                parsed_rule['sourceIpAddress'] = value
            elif key == 'source_ip_subnet_mask':
                parsed_rule['sourceIpSubnetMask'] = value
            elif key == 'destination_ip_address':
                parsed_rule['destinationIpAddress'] = value
            elif key == 'destination_ip_subnet_mask':
                parsed_rule['destinationIpSubnetMask'] = value
            elif key == 'destination_port_range_start':
                parsed_rule['destinationPortRangeStart'] = int(value)
            elif key == 'destination_port_range_end':
                parsed_rule['destinationPortRangeEnd'] = int(value)
            elif key == 'version':
                parsed_rule['version'] = int(value)
        parsed_rules.append(parsed_rule)
    return parsed_rules
663154
def _get_ip_address(self, request):
        
        ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
        if ipaddr:
            # X_FORWARDED_FOR returns client1, proxy1, proxy2,...
            return ipaddr.split(",")[0].strip()
        return request.META.get("REMOTE_ADDR", "")