Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the client IP of a Tornado request?

Tags:

python

tornado

I have a RequestHandler object for incoming post()s. How can I find the IP of the client making the request? I've browsed most of RequestHandler's methods and properties and seem to have missed something.

like image 641
mikemaccana Avatar asked Jun 24 '10 14:06

mikemaccana


2 Answers

RequestHandler.request.remote_ip (from RequestHandler's instance)

you can inspect the response like:

...
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(repr(self.request))
...
like image 180
mykhal Avatar answered Nov 16 '22 01:11

mykhal


mykhal's answer is right, however sometimes your application will be behind a proxy, for example if you use nginx and UWSGI and you will always get something like 127.0.0.1 for the remote IP. In this case you need to check the headers too, like:

remote_ip = self.request.headers.get("X-Real-IP") or \
            self.request.headers.get("X-Forwarded-For") or \
            self.request.remote_ip

Edit Oct 17th, 2019: include the commonly used header X-Forwarded-For which is used by AWS load balancers amongst others.

like image 34
3k- Avatar answered Nov 16 '22 00:11

3k-