[英]How can I get the user's IP-Address in my Cloud-Run Flask app?
I have a Flask app running via Google Cloud Run and I need to know the user's IP-Address.我有一个通过 Google Cloud Run 运行的 Flask 应用程序,我需要知道用户的 IP 地址。 I am using gunicorn as my Server.
我正在使用 gunicorn 作为我的服务器。 I have tried the following code:
我尝试了以下代码:
request.remote_addr
request.environ['REMOTE_ADDR']
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
It is returning this IP-Address: 169.254.8.129
which is not mine.它正在返回这个 IP 地址:
169.254.8.129
,这不是我的。 Is this maybe the IP of a Load-Balancer between the app and the user?这可能是应用程序和用户之间负载平衡器的 IP 吗?
And is there a way to get the correct IP-Address without having to use additional Services?有没有办法在不使用额外服务的情况下获得正确的 IP 地址?
You have headers provided by Google.您有 Google 提供的标题。 In my tests I got these 2:
在我的测试中,我得到了这两个:
X-Forwarded-For: [MyPubliCIp, LoadBalancerIp,MyPubliCIp]
Forwarded: [for="MyPubliCIp";proto=http]
Use them as you want.随心所欲地使用它们。
In Cloud Run, inside a Flask route I've done this:在 Cloud Run 中,在 Flask 路线内,我已经这样做了:
ip = request.environ.get("HTTP_X_FORWARDED_FOR", request.remote_addr)
logging.info(f"IP ADDRESS: {ip}")
With this I can get the requester public IP address.有了这个,我可以获得请求者公共 IP 地址。
request.remote_addr works in servers like App Engine. request.remote_addr 适用于 App Engine 等服务器。
I am running my service in Google App Engine, and did not get any of the above working, but this did work.我在 Google App Engine 中运行我的服务,并没有得到上述任何工作,但这确实有效。
ip = request.headers['X-Appengine-User-Ip']
This answer is to supplement copy paste-able code to the accepted answer provided by guillaume blaquiere.该答案是对 guillaume blaquiere 提供的已接受答案的补充复制粘贴代码。 Code you could use in flask to get the client source IP address from the
X-Forwarded-For
HTTP header:代码您可以在flask中获取客户来源ZA12A3079E14CED46E6E6BA52B8A90B21AZ从
X-Forwarded-For
Forwarded Z293C93C99998598598598559855985985985985985959985DDC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FC6FCFC6FCFC6FCFCNFCNFCNFCNFCFCFCFCFCFCFCAFCENFCENFCENFCNFCAFCNFCAFCER
forwarded_header = request.headers.get("X-Forwarded-For")
if forwarded_header:
source_ip = request.headers.getlist("X-Forwarded-For")[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.