Search code examples
pythonsocketswebservertornado

Bind Tornado Webserver on random port


I need run tornado web server in a random port.

Usually if a socket is bind to the port 0 the os assign a random port.

import socket
s = socket.socket()
s.bind(('',0))
print s.getsockname()
('0.0.0.0', 39727)

where 39727 is the port assigned by the OS.

how can I get this behavior using tornado?


Solution

  • Tornado passes on the port, you can call bind_sockets with a port of 0, like this:

    import tornado.httpserver
    import tornado.ioloop
    import tornado.netutil
    import tornado.web
    
    app = tornado.web.Application()
    sockets = tornado.netutil.bind_sockets(0, '')
    server = tornado.httpserver.HTTPServer(app)
    server.add_sockets(sockets)
    
    for s in sockets:
        print('Listening on %s, port %d' % s.getsockname()[:2])
    tornado.ioloop.IOLoop.instance().start()
    

    Note that you'll get different port numbers for IPv4 and IPv6. If you want IPv4 and IPv6 to be on the same port, either try port numbers yourself, or supply a list with your own socket created as in the question (create an IPv6 socket with IPV6_V6ONLY set to 0 to get both IPv6 and IPv4 on the same socket) in the place of sockets in the above.