Reputation: 16563
I have a Python 3 app on Google App Engine Standard.
I was using request.remote_addr
to get users' IP addresses and it was always returning 127.0.0.1.
I then added werkzeug ProxyFix like this:
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
I'm also using other middleware to enable cloud ndb:
app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app)
Now request.remote_addr
always returns 169.254.1.1 which is a link-local IP address.
Is there a way to fix ProxyFix to get Flask to return the correct IP address?
The X-Forwarded-For
header does have the right IP address, but I'd like to get this IP address in request.remote_addr
.
Upvotes: 4
Views: 766
Reputation: 16563
It looks like app engine has two proxies. Don't know what the second one is (one is for the load balancer).
The solution is to tell ProxyFix
to trust both proxies, and you do that this way:
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2)
Upvotes: 2
Reputation: 1343
You can use one of following options, try both of them to see which one works for you:
user_ip = request.headers.getlist("X-Forwarded-For")[0]
user_ip_2 = request.headers['x-appengine-user-ip']
Upvotes: 0
Reputation: 6323
Is it possible request.remote_addr was giving you 127.0.0.1 because you are on your dev environment (LAN)?
This doesn't answer your question - but is there a specific reason why you want to use request.remote_addr instead of X-Forwarded-For?
Upvotes: 0