James Sapam
James Sapam

Reputation: 16940

Remote client IP address in Flask

How can I get the remote / client IP in Flask running on Apache? My webservice is behind a load balancer, so request.remote_addr gives the load balancer IP instead of the client IP.

Upvotes: 0

Views: 941

Answers (2)

DavidLin3
DavidLin3

Reputation: 408

You can get the remote client ip like this:

remote_ip = request.headers.get('X-Forwarded-For')
if not remote_ip:
    remote_ip = request.remote_addr

alternative method:

remote_ip = request.environ.get('HTTP_X_FORWARDED_FOR')
if not remote_ip:
    remote_ip = request.environ.get('REMOTE_ADDR')

Upvotes: 1

yorodm
yorodm

Reputation: 4461

If your balancer is rf7239 compliant it should send a Forwarded header, if it's not, it might send X-Forwarded-For. Check any of these headers instead of REMOTE_ADDR

Upvotes: 0

Related Questions