Flask request.remote_addr is wrong on webfaction and not showing real user IP

Ignas Butėnas picture Ignas Butėnas · Oct 7, 2012 · Viewed 35.8k times · Source

I just deployed a Flask app on Webfaction and I've noticed that request.remote_addr is always 127.0.0.1. which is of course isn't of much use.

How can I get the real IP address of the user in Flask on Webfaction?

Thanks!

Answer

Ignas Butėnas picture Ignas Butėnas · Oct 7, 2012

If there is a proxy in front of Flask, then something like this will get the real IP in Flask:

if request.headers.getlist("X-Forwarded-For"):
   ip = request.headers.getlist("X-Forwarded-For")[0]
else:
   ip = request.remote_addr

Update: Very good point mentioned by Eli in his comment. There could be some security issues if you just simply use this. Read Eli's post to get more details.