Fast way to test if a port is in use using Python
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
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()
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.
Are you on Linux? If so, perhaps your application could run netstat -lant
(or netstat -lanu
if you're using UDP) and see what ports are in use. This should be faster...
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.