How to find the port a server is listening on (from within the server)

Tim Williams (gmail) tdwdotnet at gmail.com
Fri Nov 25 17:33:44 EST 2005


How can I find the port a server is listening on - at the commented line in
the code below. (ie  self.serving_on_port_num =  ????? )

I have googled a lot. :-(

------------------------------------------------------------------

class BaseSrvr(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def server_bind(self):
        """Override server_bind to store the server name."""
        try:
            SocketServer.TCPServer.server_bind(self)
            host, port = self.socket.getsockname()
            self.server_name = socket.getfqdn(host)
            self.server_port = port
        except:
            print "*******server bind except************"

class RequestHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        self.incoming_port = self.client_address[1]
#===>   self.serving_on_port_num =  ?????
# The number of the serving port not the connecting port

def StartServer(port):
    server = BaseSrvr(('', int(port) ), RequestHandler )
    server.serve_forever()

if __name__ == '__main__':

    StartServer(port)

------------------------------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20051125/a9db2bc1/attachment.html>


More information about the Python-list mailing list