linux - Verify if a local port is available in python -
i have project spawn subprocesses, again take port number bind to. port number assigned python script, take random port between 49152 , 65535.
i want verify if port available , not used other tool on local system (*nix).
from another question have snippet:
import socket; sock = socket.socket(socket.af_inet, socket.sock_stream) result = sock.connect_ex(('127.0.0.1',80)) if result == 0: print "port open" else: print "port not open"
could use in case? not open port , not close further use?
simply create temporary socket , try bind port see if it's available. close socket after validating port available.
def tryport(port): sock = socket.socket(socket.af_inet, socket.sock_stream) result = false try: sock.bind(("0.0.0.0", port)) result = true except: print("port in use") sock.close() return result
Comments
Post a Comment