Checking if port is in use.

Peter Hansen peter at engcorp.com
Sat Mar 19 12:17:24 EST 2005


Alex Polite wrote:
> On lör, mar 19, 2005 at 10:12:10 -0500, Peter Hansen wrote:
>>Alex Polite wrote:
>>
>>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.
> 
> I'm launching another server (non python) from python and I have to
> designate which port that server should bind to.

If I understand correctly, then you have only two
clear options:

1. Launch the server on whatever port, and make sure you
can identify its failure when that port is in use.
Presumably then you can just step your way through the
available ports until one of them "takes".

2. Check the port ahead of time, using the pattern of
"bind to port, catch exception if in use, release port if
not in use", then basically do #1, noting that if you
can't catch the server failing you will still have the
slight possibility that something else could grab the
port in the meantime.  I suspect that's unlikely to happen
in your case, so you can likely ignore that.

-Peter



More information about the Python-list mailing list