class PortReporter(Service, object):

    def __init__(self, factory, reportPort):
        self.factory = factory
self.reportPort = reportPort

def privilegedStartService(self):
    self.listeningPort = reactor.listenTCP(0, self.factory)
self.reportPort(self.listeningPort.getHost().port)
return super(PortReporter, self).privilegedStartService()

def stopService(self):
    self.listeningPort.stopListening()
return super(PortReporter, self).stopService()
twisted - get OS-chosen listen port