thomascirca thomascirca - 4 months ago 26
Python Question

Determining whether a request came via socket or URL with Tornado

I have a Tornado server that listens on both an address/port, and on a socket. I create the server roughly like so (stripped down heavily):

from tornado import httpserver
from tornado.netutil import bind_unix_socket

server = httpserver.HTTPserver(
request_callback=some_callback,
io_loop=some_loop,
)
unix_socket = bind_unix_socket("mysock.sock")
server.add_socket(unix_socket)
server.listen(address="some_host", port=1234)


I'd like to be able to differentiate when a request is received via the socket, ie something like:

curl -XGET --unix-socket mysock.sock http:/ping


As opposed to:

curl http://some_address:1234/ping


I looked at the HTTPServerRequest that Tornado uses when a request is received, but I'm not sure what the best way is to tell the difference between the two. I can look at
remote_ip
to see if it comes from localhost, but I don't think that's ideal.

Answer

localhost is an internet-domain interface with a well-known IP address. It's not the same as a unix-domain socket, which has no IP address.

A brief look at the source suggests that the remote_ip attribute will contain '0.0.0.0' for a connection received on the unix socket.

(The remote_ip would presumably be '127.0.0.1' for a connection received via a localhost connection.)