get open TCP port in Python

后端 未结 5 1297
走了就别回头了
走了就别回头了 2020-12-14 01:24

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

5条回答
  •  生来不讨喜
    2020-12-14 01:40

    The free port can be found by binding a socket to a port selected by the operating system. After the operating system selects a port the socket can be disposed. However, this solution is not resistant to race conditions - in the short time between getting the free port number and using this port other process may use this port.

    def find_free_port():
        s = socket.socket()
        s.bind(('', 0))            # Bind to a free port provided by the host.
        return s.getsockname()[1]  # Return the port number assigned.
    

提交回复
热议问题