How can I get the user's IP-Address in my Cloud-Run Flask app?

Viewed 1011

I have a Flask app running via Google Cloud Run and I need to know the user's IP-Address. I am using gunicorn as my Server. 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. Is this maybe the IP of a Load-Balancer between the app and the user?

And is there a way to get the correct IP-Address without having to use additional Services?

4 Answers

You have headers provided by 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:

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.

request.remote_addr works in servers like App Engine.

I am running my service in Google App Engine, and did not get any of the above working, but this did work.

ip = request.headers['X-Appengine-User-Ip']

This answer is to supplement copy paste-able code to the accepted answer provided by guillaume blaquiere. Code you could use in flask to get the client source IP address from the X-Forwarded-For HTTP header:

forwarded_header = request.headers.get("X-Forwarded-For")
if forwarded_header:                                  
    source_ip = request.headers.getlist("X-Forwarded-For")[0]
Related