Checking if port is in use.

Peter Hansen peter at
Sat Mar 19 16:12:10 CET 2005

Alex Polite wrote:
> If I try to bind a socket to a port that's already in use I get this
> error
> "error socket.error: (98, 'Address already in use')"
> Is there anyway to check in advance if a port i already taken?

In general in Python it's not considered good style to
"look before you leap".  After all, in cases like you
describe, some other could easily grab that port between
the time you discover that it's available and the time
you try to actually open the port.

There are also probably alternative approaches to what
you are trying to do, assuming it's not the case that all
you're doing is trying to avoid the exception.  (If that's
the case, just catch the exception: that's how you do it
in Python.)

You could, for example, bind to a port of "0" and that will
auto-assign an available port for you.  Does that work
in your case?  If not, please describe what you are really
trying to accomplish.


More information about the Python-list mailing list