简体   繁体   English

如何在 Django 视图中获取客户的 IP 视图

[英]How to get Client's IP in Django Views

I have piece of code to extract client IP in Django views.我有一段代码可以在 Django 视图中提取客户端 IP 。 However my code is executing only this ip = request.META.get('REMOTE_ADDR') and I am always getting 127.0.0.1 as IP.但是我的代码只执行这个 ip = request.META.get('REMOTE_ADDR') 并且我总是得到 127.0.0.1 作为 IP。 Most of the solutions I have searched used below mentioned code.我搜索过的大多数解决方案都使用了下面提到的代码。 Any other way to do it??还有什么办法可以吗??

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

The above code is correct.You are running this in your localhost and accessing from your same system thats why you are getting 127.0.0.1 as client IP.上面的代码是正确的。您在本地主机中运行它并从同一系统访问,这就是为什么您将 127.0.0.1 作为客户端 IP 获得。 If you need to verify this just try using 'ngork' and check the IP.如果您需要验证这一点,请尝试使用“ngork”并检查 IP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM