How does django get the user's ip address

created at 07-17-2021 views: 19

In the actual django development process, sometimes it is necessary to record the user's ip information, so how to get the user's real ip information in django?

method 1

The first method: get through HTTP_X_FORWARDED_FOR and REMOTE_ADDR

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]
        ip = request.META.get('REMOTE_ADDR')
    return ip

print get_client_ip(request)

Note: This method is not very safe. For abnormal users, it is easy to use this method to return their forged ip address

method 2

The second method: use the module django-ipware

install first:

pip install django-ipware

simplified example

# You can use the request object in view and middleware

  from ipware import get_client_ip
  client_ip, is_routable = get_client_ip(request)
  if client_ip is None:
     # Unable to get the ip address of the client
      # Get the client's ip
      if is_routable:
          # The client's ip address is a public address
          # The client's ip address is a private address

  # The priority order is (public, private, loopback, none)

Advanced usage:

Custom header information-used to view the custom request header of ipware

i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])

Proxy count-Django server supports a fixed number of proxies

i, r = get_client_ip(request, proxy_count=1)

Trusted proxy-Django server supports one or more known and trusted proxies

i, r = get_client_ip(request, proxy_trusted_ips=(''))

# For multiple agents, just add them to the list
i, r = get_client_ip(request, proxy_trusted_ips=('', ''))

# For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
created at:07-17-2021
edited at: 07-17-2021: