'python websockets set port as None, how can get which port used?
I used python websockets library create a websocket server, to avoid port has been used by other application, I set port as None, let system choose a port for my websocket server. My problem is how to get which port my websocket server used from program?
Solution 1:[1]
Howeverm, I don't found how to use websockets or asyncio to get port. I used netstat -ano to get the port. Here is my code:
def get_server_port():
try:
current_pid = os.getpid()
log_utils.get_logger().info(current_pid)
netstat_cmd = "netstat -ano"
outs, errs = windows_utils.run_cmd(netstat_cmd, encoding='GBK')
if errs:
log_utils.get_logger().error(errs)
else:
lines = outs.split('\r\n')
for line in lines:
temp = [i for i in line.split(' ') if i != '']
if len(temp) > 4:
if temp[4] == str(current_pid) and temp[3] == 'LISTENING':
print(temp)
address_array = temp[1].split(':')
if len(address_array) > 1:
port_str = address_array[1]
return int(port_str)
except BaseException as e:
log_utils.get_logger().exception(e)
Solution 2:[2]
I don't see anything about that in documentation, but you can get port from socket
async with websockets.serve(handler, "localhost", None) as server:
print(server.sockets[0].getsockname()[1])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rongjie Shao |
Solution 2 | Krutoy 4el |