A quick way to check if a port is being used with Python

I have a python server that listens for a couple of sockets. At startup, I try to connect to these sockets before listening, so I can be sure that nothing is using this port yet. This adds about three seconds to starting my server (it's about 0.54 seconds without a test), and I would like to trim it. Since I am only testing localhost, I think a wait time of around 50 milliseconds is more than enough for this. Unfortunately, the socket.setdefaulttimeout (50) method does not seem to work for some reason.

How can i crop this?

+4
source share
4 answers

How to simply try to bind to the correct port and handle the case of an error if the port is busy? (If the problem is that you can run the same service twice, then do not look at the open ports.)

+7
source

Here is an example of how to check if a port has been selected.

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() 
+5
source

Are you on Linux? If so, it is possible your application can run netstat -lant (or netstat -lanu if you use UDP) and see which ports are used. It should be faster ...

+1
source

Simon B's answer is a path you cannot verify, just try linking and handling the error case, if it is already in use.

Otherwise, you are in a race state when some other application may capture the port between your check so that it is free and your subsequent attempt to associate with it. This means that you still have to handle the possibility that your call cannot be connected, so checking in advance has not been achieved.

0
source

Source: https://habr.com/ru/post/1304469/


All Articles