pythontcptcp-port

get open TCP port in Python


I want to get any random open TCP port on localhost in Python. What is the easiest way?


Solution

  • My current solution:

    def get_open_port():
            import socket
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(("",0))
            s.listen(1)
            port = s.getsockname()[1]
            s.close()
            return port
    

    Not very nice and also not 100% correct but it works for now.