title: twisted - get OS-chosen listen port
body: <p>I am writing a twisted P2P client using the application framework. The listen port for incoming connections will be on a random (OS-determined) port. However, I need a way to determine what that port is after creating it:</p>
  
  <pre><code>import twisted... etc.
  
  application = service.Application('vmesh')
  peerservice = MyPeerService()
  servicecollection = service.IServiceCollection(application)
  factory = MyPeerFactory(peerservice)
  server = internet.TCPServer(0, factory) # listen on random port
  listen_port = server.getHost().port # ??? doesn't work...
  server.setServiceParent(servicecollection)
  </code></pre>
  
  <p>I can't find anything in the docs about querying the port created by <code>internet.TCPServer()</code> or by <code>reactor.listenTCP()</code> which it forwards to. I can't simply wait for a connection to occur since the client has to announce its port in order for those connections to ever happen.</p>