In my tornado-based application I need to store the server's IP-address (e.g. the address that was used by the user to connect to the server) in session. How to determine this IP-address in Tornado? I'm using Tornado 2.4.1.
If you don't mind throwing in some dependencies, you can do this from a request handler:
import socket
import urlparse
hostname = urlparse.urlparse("%s://%s"
% (self.request.protocol, self.request.host)).hostname
ip_address = socket.gethostbyname(hostname)
An important thing to note here is that self.request.host
can include a port number. That's why it is preferred to parse it using urlparse
.