1

Question

Similar to this question - On localhost, how do I pick a free port number?

Except Twisted abstracts away access to socket behind reactor methods like listenTCP or the UDP equivalent and I haven't found a mechanism where I can just tell the reactor to find a free socket and bind/listen to it.

Community
  • 1
  • 1
David
  • 17,673
  • 10
  • 68
  • 97
  • Normally you do not want to use a random port for a server, otherwise how will you connect to it. if you really want a random port, then generate a random number, assign a socket to it, then test if it was successful. – ron Dec 10 '19 at 09:50
  • @smac89 Originally it was related to 0MQ but I dropped that part of the question and have fixed most of the tags. – David Dec 11 '19 at 15:14
  • @ron I wrote a desktop process manager that spools up various twisted.web.Site applications on demand and they all emit to stderr a magic token that tells the manager which port the app is running on. Similarly I am working on a project that uses multiple 0mq listening sockets to coordinate work between multiple processes and they all check into something like hadoop's zookeeper to report their address and port #'s – David Dec 11 '19 at 15:19

1 Answers1

3

Like so:

reactor.listenTCP(0, ...)
Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
  • Thank you, I've read large chunks of Twisted's source but that one eluded me. – David Dec 11 '19 at 15:21
  • Is there a respectable way to find the port number? I know that the object returned by `listenTCP` has a private attribute `_realPortNumber`, but is there a way to get it without using that? – Peter Westlake Dec 16 '19 at 17:07
  • P.S. This is for a unit test for an HTTP client's GET method, and the idea is to find an unused port, publish a web server on it, and get that. – Peter Westlake Dec 16 '19 at 17:15
  • @PeterWestlake the easiest is to grab the returned object from listenTCP - https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IListeningPort.html – David Dec 16 '19 at 18:24
  • 1
    Unit tests probably don't bind real HTTP ports. Perhaps take a look at treq's RequestTraversalAgent. – Jean-Paul Calderone Dec 16 '19 at 19:02