I want to get any random open TCP port on localhost in Python. What is the easiest way?
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.
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.
import socket def find_free_port(): with socket.socket() as s: s.bind(('', 0)) # Bind to a free port provided by the host. return s.getsockname()[1] # Return the port number assigned.
https://godbolt.org/z/fs13K13dG
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With