The HTTP headers X-Forwarded-For (XFF)
or REMOTE_ADDR
are used to get the original requested IP address.
The IP address stored in the header will be a comma separated list of IP addresses. For example, ip_addr_1, ip_addr_2, ip_addr_3
.
In Django, the request headers are obtained from the request object using the META
attribute of the request object.
HttpRequest.META
The META
attribute returns a dictionary consisting of all available HTTP headers.
Only relevant code to obtain the IP address given the request object is shown. The code can be placed at relevant places in the Django app to get the client’s IP address.
def get_client_ip_address(request):req_headers = request.METAx_forwarded_for_value = req_headers.get('HTTP_X_FORWARDED_FOR')if x_forwarded_for_value:ip_addr = x_forwarded_for_value.split(',')[-1].strip()else:ip_addr = req_headers.get('REMOTE_ADDR')return ip_addr
META
attribute dictionary, we obtain the value for the HTTP header HTTP_X-Forwarded-For
.HTTP_X-Forwarded-For
is none, then we can get the IP using the REMOTE_ADDR
header.Note that above function assumes that the last IP address in the HTTP_X_FORWARDED_FOR
header is the original client IP address, which may not always be the case. In some cases, the HTTP_X_FORWARDED_FOR
header may contain a list of IP addresses, and the original client IP address may be somewhere in the middle of the list. Additionally, some proxies may overwrite the HTTP_X_FORWARDED_FOR
header, or remove it entirely. As a result, this function may not always return the correct client IP address in all situations.
Here is another way to get the IP address of the client i.e use a third-party package like django-ipware
.This can handle a variety of situations where the IP address may be obscured or hidden behind proxies or load balancers.
To use django-ipware
, you can install it using pip:
pip install django-ipware
Then in your Django view, you can import the get_client_ip
function from ipware
and use it to retrieve the client IP address:
from ipware import get_client_ipdef my_view(request):# Get the client IP addressclient_ip, is_routable = get_client_ip(request)# Do something with the client IP address...return ...
The get_client_ip
function returns a tuple containing the client IP address as a string and a boolean value indicating whether the IP address is a routable (public) address or a private (non-routable) address.
This method is more reliable than using the REMOTE_ADDR
and HTTP_X_FORWARDED_FOR
headers, as it can handle situations where the IP address is obscured or hidden by proxies or load balancers.