tags:

views:

84

answers:

3

I have a python server that listens on a couple sockets. At startup, I try to connect to these sockets before listening, so I can be sure that nothing else is already using that port. This adds about three seconds to my server's startup (which is about .54 seconds without the test) and I'd like to trim it down. Since I'm only testing localhost, I think a timeout of about 50 milliseconds is more than ample for that. Unfortunately, the socket.setdefaulttimeout(50) method doesn't seem to work for some reason.

How I can trim this down?

+3  A: 

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.)

Simon B.
This certainly makes the most sense, but I can't get the darned thing to throw an error when I bind the same port twice.
directedition
A: 

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...

Mox
:::Tests::: `netstat` seems to be work fine on Vista to do much the same thing.
Brian
A: 

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.

joefis