Fast way to test if a port is in use using Python
Here is an example of how to check if the port is taken.
import socket, errno
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("127.0.0.1", 5555))
except socket.error as e:
if e.errno == errno.EADDRINUSE:
print("Port is already in use")
else:
# something else raised the socket.error exception
print(e)
s.close()
To check port use:
def is_port_in_use(port: int) -> bool:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0
source: https://codereview.stackexchange.com/questions/116450/find-available-ports-on-localhost
Note: connect_ex cann still raise an exception (in case of bad host name i.e see docs on [1].
[1] https://docs.python.org/3/library/socket.html
Simon B's answer is the way to go - don't check anything, just try to bind and handle the error case if it's already in use.
Otherwise you're in a race condition where some other app can grab the port in between your check that it's free and your subsequent attempt to bind to it. That means you still have to handle the possibility that your call to bind will fail, so checking in advance achieved nothing.
How about just trying to bind to the port you want, and handle the error case if the port is occupied? (If the issue is that you might start the same service twice then don't look at open ports.)
This is the reasonable way also to avoid causing a race-condition, as @eemz said in another answer.