Pradeepb
Pradeepb

Reputation: 2562

get Client IP in a flask based application

I have Flask application deployed in server. and we are using Nginx. nginx setup is as below:

proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_read_timeout 25s;
proxy_pass http://127.0.0.1:8000;
add_header X-Cache $upstream_cache_status;

In Flask setup I have done the following :

app = Flask(__name__, static_folder=None)
app.wsgi_app = ProxyFix(app.wsgi_app)

Now, whenever user visits a site, I want a real ip. Currently I am getting

127.0.0.1

I have tried like below:

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

Could anybody guide me here please.

Upvotes: 2

Views: 5140

Answers (2)

BERMAK
BERMAK

Reputation: 31

You should just have:

ip = request.access_route[-1]

Upvotes: 2

pjcunningham
pjcunningham

Reputation: 8046

Use request.access_route

https://github.com/pallets/werkzeug/blob/master/werkzeug/wrappers.py

@cached_property
def access_route(self):
    """If a forwarded header exists this is a list of all ip addresses
    from the client ip to the last proxy server.
    """
    if 'HTTP_X_FORWARDED_FOR' in self.environ:
        addr = self.environ['HTTP_X_FORWARDED_FOR'].split(',')
        return self.list_storage_class([x.strip() for x in addr])
    elif 'REMOTE_ADDR' in self.environ:
        return self.list_storage_class([self.environ['REMOTE_ADDR']])
    return self.list_storage_class()

Example Nginx config:

location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Protocol https;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:9000;
}

Upvotes: 7

Related Questions