How do I get user IP address in django?

后端 未结 11 1159
野趣味
野趣味 2020-11-22 15:33

How do I get user\'s IP in django?

I have a view like this:

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template impor         


        
11条回答
  •  遇见更好的自我
    2020-11-22 16:15

    I was also missing proxy in above answer. I used get_ip_address_from_request from django_easy_timezones.

    from easy_timezones.utils import get_ip_address_from_request, is_valid_ip, is_local_ip
    ip = get_ip_address_from_request(request)
    try:
        if is_valid_ip(ip):
            geoip_record = IpRange.objects.by_ip(ip)
    except IpRange.DoesNotExist:
        return None
    

    And here is method get_ip_address_from_request, IPv4 and IPv6 ready:

    def get_ip_address_from_request(request):
        """ Makes the best attempt to get the client's real IP or return the loopback """
        PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.')
        ip_address = ''
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
        if x_forwarded_for and ',' not in x_forwarded_for:
            if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for):
                ip_address = x_forwarded_for.strip()
        else:
            ips = [ip.strip() for ip in x_forwarded_for.split(',')]
            for ip in ips:
                if ip.startswith(PRIVATE_IPS_PREFIX):
                    continue
                elif not is_valid_ip(ip):
                    continue
                else:
                    ip_address = ip
                    break
        if not ip_address:
            x_real_ip = request.META.get('HTTP_X_REAL_IP', '')
            if x_real_ip:
                if not x_real_ip.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_real_ip):
                    ip_address = x_real_ip.strip()
        if not ip_address:
            remote_addr = request.META.get('REMOTE_ADDR', '')
            if remote_addr:
                if not remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr):
                    ip_address = remote_addr.strip()
        if not ip_address:
            ip_address = '127.0.0.1'
        return ip_address
    

提交回复
热议问题