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

Asked By: illright

||

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.

Answered By: hjpotter92

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
Answered By: Fabien Snauwaert
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.