Alb*_*ert 46
我目前的解决方案
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
Run Code Online (Sandbox Code Playgroud)
不是很好,也不是100%正确但它现在有效.
通过将套接字绑定到操作系统选择的端口,可以找到空闲端口.在操作系统选择端口后,可以处理插座.但是,此解决方案不能抵抗竞争条件 - 在获取空闲端口号和使用此端口之间的短时间内,其他进程可能会使用此端口.
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.
Run Code Online (Sandbox Code Playgroud)