Python get client ip

55 Python code examples are found related to " get client ip". 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.
Example 1
Source File: util.py    From dHydra with Apache License 2.0 6 votes vote down vote up
def get_client_ip():
    while True:
        try:
            response = requests.get(
                'https://ff.sinajs.cn/?_=%s&list=sys_clientip'
                % int(time.time() * 1000)).text
            ip = re.findall(r'\"(.*)\"', response)
            break
        except Exception as e:
            print("get_client_ip: {}".format(e))
            try:
                ip = _get_public_ip()
                return ip
            except Exception as e:
                print("_get_client_ip: {}".format(e))
    return ip[0] 
Example 2
Source File: utils.py    From colossus with MIT License 6 votes vote down vote up
def get_client_ip(request: HttpRequest) -> str:
    """
    Inspects an HTTP Request object and try to determine the client's IP
    address.

    First look for the "HTTP_X_FORWARDED_FOR" header. Note that due to
    application server configuration this value may contain a list of IP
    addresses. If that's the case, return the first IP address in the list.

    The result may not be 100% correct in some cases. Known issues with Heroku
    service:
    https://stackoverflow.com/questions/18264304/

    If there is no "HTTP_X_FORWARDED_FOR" header, falls back to "REMOTE_ADDR"

    :param request: An HTTP Request object
    :return: The client IP address extracted from the HTTP Request
    """
    x_forwarded_for: Optional[str] = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip 
Example 3
Source File: DHCP.py    From piSociEty with GNU General Public License v3.0 6 votes vote down vote up
def get_client_ip(self, xid, dhcp_options):
        try:
            field_name, req_addr = dhcp_options[2]
            if field_name == 'requested_addr':
                return 'requested', req_addr

            raise ValueError
        except ValueError:
            for field in dhcp_options:
                if (field is tuple) and (field[0] == 'requested_addr'):
                    return field[1]

        if xid in self.dhcp_dic.keys():
            client_ip = self.dhcp_dic[xid]
            return 'stored', client_ip

        net = IPNetwork(self.ip_address + '/24')
        return 'generated', str(random.choice(list(net))) 
Example 4
Source File: auth.py    From django-heartbeat with MIT License 6 votes vote down vote up
def get_client_ip(request):
    access_route = get_access_route(request)

    if len(access_route) == 1:
        return access_route[0]
    expression = """
        (^(?!(?:[0-9]{1,3}\.){3}[0-9]{1,3}$).*$)|  # will match non valid ipV4
        (^127\.0\.0\.1)|  # will match 127.0.0.1
        (^10\.)|  # will match 10.0.0.0 - 10.255.255.255 IP-s
        (^172\.1[6-9]\.)|  # will match 172.16.0.0 - 172.19.255.255 IP-s
        (^172\.2[0-9]\.)|  # will match 172.20.0.0 - 172.29.255.255 IP-s
        (^172\.3[0-1]\.)|  # will match 172.30.0.0 - 172.31.255.255 IP-s
        (^192\.168\.)  # will match 192.168.0.0 - 192.168.255.255 IP-s
    """
    regex = re.compile(expression, re.X)
    for ip in access_route:
        if not ip:
            # it's possible that the first value from X_FORWARDED_FOR
            # will be null, so we need to pass that value
            continue
        if regex.search(ip):
            continue
        else:
            return ip 
Example 5
Source File: utils.py    From explorer with Apache License 2.0 6 votes vote down vote up
def get_client_ip(request):
    """
    Get IP from a request
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip 
Example 6
Source File: api_external.py    From nmeta with Apache License 2.0 6 votes vote down vote up
def get_flow_client_ip(self, flow_hash):
        """
        Find the IP that is the originator of a flow searching
        forward by flow_hash

        Finds first packet seen for the flow_hash within the time
        limit and returns the source IP, otherwise 0,
        """
        db_data = {'flow_hash': flow_hash,
              'timestamp': {'$gte': datetime.datetime.now() - FLOW_TIME_LIMIT}}
        packets = self.packet_ins.find(db_data).sort('$natural', 1).limit(1)
        if packets.count():
            return list(packets)[0]['ip_src']
        else:
            self.logger.warning("no packets found")
            return 0 
Example 7
Source File: wsgi.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_client_ip(environ):
    # type: (Dict[str, str]) -> Optional[Any]
    """
    Infer the user IP address from various headers. This cannot be used in
    security sensitive situations since the value may be forged from a client,
    but it's good enough for the event payload.
    """
    try:
        return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip()
    except (KeyError, IndexError):
        pass

    try:
        return environ["HTTP_X_REAL_IP"]
    except KeyError:
        pass

    return environ.get("REMOTE_ADDR") 
Example 8
Source File: success2pass.py    From scripts with MIT License 6 votes vote down vote up
def get_client_ip(request):
    """
    A method to get the cient ip address.
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    elif request.META.get('HTTP_X_REAL_IP'):
        ip = request.META.get('HTTP_X_REAL_IP')
    else:
        ip = request.META.get('REMOTE_ADDR')

    # if you want add range /24 to the rule:
    # s = ip.split(".")
    # ip = "{}.{}.{}.0/24".format(s[0], s[1], s[2])
    return ip 
Example 9
Source File: utils.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def get_client_ip(request):
    """
    Get a client's IP address from a request.

    If settings.NUM_PROXIES is 0, reads directly from REMOTE_ADDR. If
    settings.NUM_PROXIES is non-zero, parses X-Forwarded-For header
    based on the number of proxies.
    """
    if settings.NUM_PROXIES == 0:
        return request.META.get("REMOTE_ADDR")
    else:
        try:
            ips = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")
            ips = [ip.strip() for ip in ips]
            return ips[-settings.NUM_PROXIES]
        except IndexError:
            return None 
Example 10
Source File: middleware.py    From django-web-profiler with MIT License 5 votes vote down vote up
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip 
Example 11
Source File: http.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getClientIP(self):
        """
        Return the IP address of the client who submitted this request.

        @returns: the client IP address
        @rtype: C{str}
        """
        if isinstance(self.client, address.IPv4Address):
            return self.client.host
        else:
            return None 
Example 12
Source File: utils.py    From django-antispam with MIT License 5 votes vote down vote up
def get_client_ip(request):
    """
    Get client ip address.

    Detect ip address provided by HTTP_X_REAL_IP, HTTP_X_FORWARDED_FOR
    and REMOTE_ADDR meta headers.

    :param request: django request
    :return: ip address
    """

    real_ip = request.META.get('HTTP_X_REAL_IP')
    if real_ip:
        return real_ip

    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        return x_forwarded_for.split(',')[0]

    return request.META.get('REMOTE_ADDR') 
Example 13
Source File: django_utils.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def get_client_ip(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip 
Example 14
Source File: utils.py    From aiohttp-login with ISC License 5 votes vote down vote up
def get_client_ip(request):
    try:
        ips = request.headers['X-Forwarded-For']
    except KeyError:
        ips = request.transport.get_extra_info('peername')[0]
    return ips.split(',')[0] 
Example 15
Source File: request.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def get_client_ip(self, request):
        """ get's the client IP address note! This never gets
            stored!!
        """
        try:
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
        except:
            ip = None
        return ip 
Example 16
Source File: http.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def getClientIP(self):
        if isinstance(self.client, address.IPv4Address):
            return self.client.host
        else:
            return None 
Example 17
Source File: utils.py    From django-maintenance-mode with MIT License 5 votes vote down vote up
def get_client_ip_address(request):
    """
    Get the client IP Address.
    """
    return request.META['REMOTE_ADDR'] 
Example 18
Source File: config.py    From power-up with Apache License 2.0 5 votes vote down vote up
def get_depl_netw_client_brg_ip(self, index=None):
        """Get deployer networks client bridge_ipaddr
        Args:
            index (int, optional): List index

        Returns:
            str: Bridge IP address
        """

        return self._get_members(
            self.cfg.deployer.networks.client,
            self.CfgKey.BRIDGE_IPADDR,
            index) 
Example 19
Source File: utils.py    From Geolocator-2 with MIT License 5 votes vote down vote up
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for is not None:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    ip_address = ip or GEO_DEFAULT_IP
    if str(ip_address) == '127.0.0.1':
        ip_address = GEO_DEFAULT_IP
    return ip_address 
Example 20
Source File: run_helper.py    From dockit with GNU General Public License v2.0 5 votes vote down vote up
def get_client_ip():
    try:
        clients = rh_config_dict['CLIENT_IP_ADDRS']
    except:
        logger.critical('Unable to find client IP address.')
        sys.exit(1)

    clients_set = set([])
    for client in clients.split(','):
        clients_set.add(client)

    return list(clients_set)


# get the prefix path to install gluster 
Example 21
Source File: utils.py    From Zilliqa-Mining-Proxy with GNU General Public License v3.0 5 votes vote down vote up
def get_client_ip(request):
    try:
        ips = request.headers["X-Forwarded-For"]
    except KeyError:
        ips = request.transport.get_extra_info("peername")[0]
    return ips.split(',')[0] 
Example 22
Source File: utils.py    From mapstory with GNU General Public License v3.0 5 votes vote down vote up
def get_client_ip(request):
    """get client ip from reguest"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip 
Example 23
Source File: middleware.py    From DjanGoat with MIT License 5 votes vote down vote up
def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip 
Example 24
Source File: utils.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def get_client_ip(request):
    """
    http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')

    return ip 
Example 25
Source File: utils.py    From youtube-audio-dl with MIT License 5 votes vote down vote up
def get_client_ip(request):
    """
    Retrieve the client's IPv4 address from the request object.
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip 
Example 26
Source File: utils.py    From astrobin with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip 
Example 27
Source File: utils.py    From rotest with MIT License 5 votes vote down vote up
def get_client_ip(request):
    """Get client's ip address.

    Returns:
        str. ip address of the client.
    """
    ip_chain = request.META.get("HTTP_X_FORWARDED_FOR")  # forward ip
    if ip_chain:
        ip_address = ip_chain.split(",")[0]

    else:
        ip_address = request.META.get("REMOTE_ADDR")

    return ip_address 
Example 28
Source File: event.py    From coding-events with MIT License 5 votes vote down vote up
def get_client_ip(forwarded=None, remote=None):
    if settings.DEBUG and remote == '127.0.0.1':
        return '93.103.53.11'
    if forwarded:
        return forwarded.split(',')[0]
    return remote 
Example 29
Source File: user.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def get_client_ip(self):
        x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for and x_forwarded_for.split(','):
            client_ip = x_forwarded_for.split(',')[0]
        else:
            client_ip = self.request.META.get('REMOTE_ADDR')

        return client_ip or '' 
Example 30
Source File: utils.py    From django-ads with Apache License 2.0 5 votes vote down vote up
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR', '')
    return ip 
Example 31
Source File: server.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_client_ip(self):
		"""
		Intelligently get the IP address of the HTTP client, optionally
		accounting for proxies that may be in use.

		:return: The clients IP address.
		:rtype: str
		"""
		address = self.client_address[0]
		header_name = self.config.get_if_exists('server.client_ip_header')                 # new style
		header_name = header_name or self.config.get_if_exists('server.client_ip_cookie')  # old style
		if not header_name:
			return address
		header_value = self.headers.get(header_name, '')
		if not header_value:
			return address
		header_value = header_value.split(',')[0]
		header_value = header_value.strip()
		if header_value.startswith('['):
			# header_value looks like an IPv6 address
			header_value = header_value.split(']:', 1)[0]
		else:
			# treat header_value as an IPv4 address
			header_value = header_value.split(':', 1)[0]
		if ipaddress.is_valid(header_value):
			address = header_value
		return address 
Example 32
Source File: helpers.py    From Pytition with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

# Get the user of the current session 
Example 33
Source File: utils.py    From wagtail-personalisation with MIT License 5 votes vote down vote up
def get_client_ip(request):
    try:
        func = import_string(settings.WAGTAIL_PERSONALISATION_IP_FUNCTION)
    except AttributeError:
        pass
    else:
        return func(request)
    try:
        x_forwarded_for = request.META['HTTP_X_FORWARDED_FOR']
        return x_forwarded_for.split(',')[-1].strip()
    except KeyError:
        return request.META['REMOTE_ADDR'] 
Example 34
Source File: rasp_result.py    From openrasp-iast with Apache License 2.0 5 votes vote down vote up
def get_client_ip(self):
        """
        获取当前请求的client ip(由header中client-ip获取), 不存在时返回空

        Returns:
            string, 获取的ip
        """
        return self.rasp_result_dict["context"].get("clientIp", "") 
Example 35
Source File: config.py    From power-up with Apache License 2.0 5 votes vote down vote up
def get_depl_netw_client_intf_ip(self, index=None):
        """Get deployer networks client interface_ipaddr
        Args:
            index (int, optional): List index

        Returns:
            str: Interface IP address
        """

        return self._get_members(
            self.cfg.deployer.networks.client,
            self.CfgKey.INTERFACE_IPADDR,
            index) 
Example 36
Source File: http.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def getClientIP(self):
        """
        Return the IP address of the client who submitted this request.

        This method is B{deprecated}.  Use L{getClientAddress} instead.

        @returns: the client IP address
        @rtype: C{str}
        """
        if isinstance(self.client, (address.IPv4Address, address.IPv6Address)):
            return self.client.host
        else:
            return None 
Example 37
Source File: util.py    From SinaL2 with Apache License 2.0 5 votes vote down vote up
def get_client_ip():
    while True:
        try:
            response = requests.get(
                'https://ff.sinajs.cn/?_=%s&list=sys_clientip'
                % int(time.time() * 1000)).text
            ip = re.findall(r'\"(.*)\"', response)
            break
        except Exception as e:
            try:
                ip = _get_public_ip()
                return ip
            except:
                pass
    return ip[0] 
Example 38
Source File: location.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_client_ip(request):
    x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
    if x_forwarded_for:
        ip = x_forwarded_for.split(",")[0]
    else:
        ip = request.META.get("REMOTE_ADDR")
    return ip 
Example 39
Source File: views.py    From Django-Blog-Python-Learning with GNU General Public License v2.0 5 votes vote down vote up
def get_client_ip(self):
        ip = self.request.META.get("HTTP_X_FORWARDED_FOR", None)
        if ip:
            ip = ip.split(", ")[0]
        else:
            ip = self.request.META.get("REMOTE_ADDR", "")
        return ip 
Example 40
Source File: local_container.py    From gigantum-client with MIT License 5 votes vote down vote up
def get_gigantum_client_ip(self) -> Optional[str]:
        """Method to get the monitored lab book container's IP address on the Docker bridge network

        Returns:
            str of IP address
        """
        clist: List[Container] = [c for c in self._client.containers.list()
                                  if 'gigantum.labmanager' in c.name
                                  # This catches the client container name during development w/ docker-compose
                                  or 'developer_labmanager' in c.name
                                  and 'gmlb-' not in c.name]
        if len(clist) != 1:
            raise ContainerException("Cannot find distinct Gigantum Client Labmanager container")

        return self.query_container_ip(clist[0].id) 
Example 41
Source File: config.py    From power-up with Apache License 2.0 5 votes vote down vote up
def get_depl_netw_client_cont_ip(self, index=None):
        """Get deployer networks client container_ipaddr
        Args:
            index (int, optional): List index

        Returns:
            str: Container IP address
        """

        return self._get_members(
            self.cfg.deployer.networks.client,
            self.CfgKey.CONTAINER_IPADDR,
            index) 
Example 42
Source File: __init__.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_client_ip(request, proxy_settings):
    """
    Take the request and the proxy_settings and determine the new client IP.

    :param request:
    :param proxy_settings: The proxy settings from OverrideAuthorizationClient
    :return: IP address as string
    """
    # This is not so easy, because we want to support the X-Forwarded-For protocol header set by proxies,
    # but also want to prevent rogue clients from spoofing their IP address, while also supporting the
    # "client" request parameter.
    # From the X-Forwarded-For header, we determine the path to the actual client, i.e. the list of proxy servers
    # that the HTTP response will pass through, including the final client IP:
    # If a client C talks to a proxy P1, which in turn talks to a proxy P2, which talks to privacyIDEA,
    # X-Forwarded-For will be "C, P1", the HTTP client IP will be P2, and path_to_client
    # consequently will be [P2, P1, C].
    # However, if we get such a request, we cannot be sure if the X-Forwarded-For header is correct,
    # or if it was sent by a rogue client in order to spoof its IP address.
    # To prevent IP spoofing, privacyIDEA allows to configure a list of proxies that are allowed to override the
    # authentication client. See ``check_proxy`` for more details.
    # If we are handling a /validate/ or /auth/ endpoint and a "client" parameter is provided,
    # it is appended to the path to the client.
    if proxy_settings:
        if not request.access_route:
            # This is the case for tests
            return None
        elif request.access_route == [request.remote_addr]:
            # This is the case if no X-Forwarded-For header is provided
            path_to_client = [request.remote_addr]
        else:
            # This is the case if a X-Forwarded-For header is provided.
            path_to_client = [request.remote_addr] + list(reversed(request.access_route))
        # A possible ``client`` parameter is appended to the *end* of the path to client.
        if (not hasattr(request, "blueprint") or
            request.blueprint in ["validate_blueprint", "ttype_blueprint",
                                  "jwtauth"]) \
                and "client" in request.all_data:
            path_to_client.append(request.all_data["client"])
        # We now refer to ``check_proxy`` to extract the mapped IP from ``path_to_client``.
        return str(check_proxy([IPAddress(ip) for ip in path_to_client], proxy_settings))
    else:
        # If no proxy settings are defined, we do not map any IPs anyway.
        return request.remote_addr