How to get the IP address of the request to a Heroku app?
Question:
Heroku has a routing system to forward requests to the dynos. My application needs to know from where the request came, but it always gets random addresses in a network, probably Heroku’s internals.
And I see that in the logs, it (Heroku’s router) gets my IP address and forwards the request. Is there a way to get the actual IP address of a request?
My application is written in Python, using Flask
Answers:
Checking Flask’s documentation on filtering headers etc., I found that:
request.headers['X-Forwarded-For']
is where you’ll get the client’s real IP address.
From a deleted comment by OP, this article provides a safer solution.
You want to preserve the IP from request.remote_addr
when locally or if hosting the site somewhere else:
def getIP():
if 'X-Forwarded-For' in request.headers:
return request.headers['X-Forwarded-For']
return request.remote_addr
Heroku has a routing system to forward requests to the dynos. My application needs to know from where the request came, but it always gets random addresses in a network, probably Heroku’s internals.
And I see that in the logs, it (Heroku’s router) gets my IP address and forwards the request. Is there a way to get the actual IP address of a request?
My application is written in Python, using Flask
Checking Flask’s documentation on filtering headers etc., I found that:
request.headers['X-Forwarded-For']
is where you’ll get the client’s real IP address.
From a deleted comment by OP, this article provides a safer solution.
You want to preserve the IP from request.remote_addr
when locally or if hosting the site somewhere else:
def getIP():
if 'X-Forwarded-For' in request.headers:
return request.headers['X-Forwarded-For']
return request.remote_addr