Naively yank the first IP address in an X-Forwarded-For header
    and assume this is correct.

    Note: Don't use this in security sensitive situations since this
    value may be forged from a client.
513404
def get_client_ip(request):
    
    try:
        return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
    except (KeyError, IndexError):
        return request.META.get('REMOTE_ADDR')
400414
private int computeNetworkPrefixFromMask(IPAddress mask) {
		
		int result = 0;
		int tmp = mask.getIPAddress();
		
		while ((tmp & 0x00000001) == 0x00000001) {
			result++;
			tmp = tmp >>> 1;
		}
		
		if (tmp != 0) {
			return -1;
		}
		
		return result;
	}
624686
private function getForwardedHeaderIp(string $header)
    {
        foreach (array_reverse(array_map('trim', explode(',', strtolower($header)))) as $values) {
            foreach (array_reverse(array_map('trim', explode(';', $values))) as $directive) {
                if (strpos($directive, 'for=') !== 0) {
                    continue;
                }

                $ip = trim(substr($directive, 4));

                if (self::isValid($ip) && !$this->isInProxiedIps($ip)) {
                    return $ip;
                }
            }
        }
    }
452935
public boolean isXForwardedHeaderRequired() {
        return forwardedHeader == null && (xForwardedForHeader != null || xForwardedByHeader != null ||
                xForwardedHostHeader != null || xForwardedProtoHeader != null);
    }
1326745
def __ip_addr(addr, address_family=socket.AF_INET):
    '''
    
    '''
    mask_max = '32'
    if address_family == socket.AF_INET6:
        mask_max = '128'

    try:
        if '/' not in addr:
            addr = '{addr}/{mask_max}'.format(addr=addr, mask_max=mask_max)
    except TypeError:
        return False

    ip, mask = addr.rsplit('/', 1)

    # Verify that IP address is valid
    try:
        socket.inet_pton(address_family, ip)
    except socket.error:
        return False

    # Verify that mask is valid
    try:
        mask = int(mask)
    except ValueError:
        return False
    else:
        if not 1 <= mask <= int(mask_max):
            return False

    return True
165309
def get_ip(request, real_ip_only=False, right_most_proxy=False):
    
    best_matched_ip = None
    warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning)
    for key in defs.IPWARE_META_PRECEDENCE_ORDER:
        value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
        if value is not None and value != '':
            ips = [ip.strip().lower() for ip in value.split(',')]
            if right_most_proxy and len(ips) > 1:
                ips = reversed(ips)
            for ip_str in ips:
                if ip_str and is_valid_ip(ip_str):
                    if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):
                        return ip_str
                    if not real_ip_only:
                        loopback = defs.IPWARE_LOOPBACK_PREFIX
                        if best_matched_ip is None:
                            best_matched_ip = ip_str
                        elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):
                            best_matched_ip = ip_str
    return best_matched_ip
119740
def is_valid_ip(ip_address):
    
    valid = True
    try:
        socket.inet_aton(ip_address.strip())
    except:
        valid = False
    return valid
388194
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.extend([str(addr) for addr in list(netaddr.IPNetwork(ip))])
      else:
        self.logger.warning('Could not parse IP address: "%s".', ip)
    return addresses
578493
def AddForwardedIp(self, address, interface):
    
    for ip in list(netaddr.IPNetwork(address)):
      self._RunIfconfig(args=[interface, 'alias', '%s/32' % str(ip)])
1172899
def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None):
    
    desired = self.ip_forwarding_utils.ParseForwardedIps(forwarded_ips)
    configured = self.ip_forwarding_utils.GetForwardedIps(
        interface, interface_ip)
    to_add = sorted(set(desired) - set(configured))
    to_remove = sorted(set(configured) - set(desired))
    self._LogForwardedIpChanges(
        configured, desired, to_add, to_remove, interface)
    self._AddForwardedIps(to_add, interface)
    self._RemoveForwardedIps(to_remove, interface)
911989
def GetForwardedIps(self, interface, interface_ip=None):
    
    try:
      ips = netifaces.ifaddresses(interface)
      ips = ips[netifaces.AF_INET]
    except (ValueError, IndexError):
      return []
    forwarded_ips = []
    for ip in ips:
      if ip['addr'] != interface_ip:
        full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits())
        forwarded_ips.append(full_addr)
    return self.ParseForwardedIps(forwarded_ips)
1185399
def is_address_in_network(ip, net):
    """"""
    # http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python
    import socket
    import struct
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    if int(bits) == 0:
        return True
    net = struct.unpack('=L', socket.inet_aton(netaddr))[0]

    mask = ((2L << int(bits) - 1) - 1)

    return (ipaddr & mask) == (net & mask)
537608
public static String ipAddress(Request request) {
        String ipAddress = request.header("x-forwarded-for");
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("Proxy-Client-IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("WL-Proxy-Client-IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("X-Real-IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("HTTP_CLIENT_IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("HTTP_X_FORWARDED_FOR");
        }
        return ipAddress;
    }
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
403088
def ip_bracket(addr):
    '''
    
    '''
    addr = ipaddress.ip_address(addr)
    return ('[{}]' if addr.version == 6 else '{}').format(addr)
424606
def is_requestaddress_in_networks(request, networks):
    """"""
    from ipware.ip import get_real_ip, get_ip

    # Get the real IP, i.e. no reverse proxy, no nginx
    ip = get_real_ip(request)
    if not ip:
        ip = get_ip(request)
        if not ip:
            return False

    # For all networks
    for network in networks:
        if is_address_in_network(ip, network):
            return True

    return False
790209
def is_ip_addr(self, ipstr):
        
        ipstr_chunks = ipstr.split('.')
        if len(ipstr_chunks) != 4:
            return False
        for ipstr_chunk in ipstr_chunks:
            if not ipstr_chunk.isdigit():
                return False
            ipno_part = int(ipstr_chunk)
            if ipno_part < 0 or ipno_part > 255:
                return False
        return True