detecting socket in use on localhost
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Oct 4 22:01:46 EDT 2004
Berends wrote:
> Wrote the code. Seems to be working just fine:
>
> [code]
> def determineAvailablePort():
> t = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> t.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>
> # Set the first port to bind to, to the minimum port in the range.
> prt = 16000
> isConnected = False
> while not isConnected:
> try:
> t.bind( (myInfo["host"], prt ) )
> isConnected = True
> t.close()
> del t
> except socket.error:
> prt += 1
> if prt > 16029:
> raise Exception
>
> return prt
> [/code]
You might want to hang on to the port, so that you don't get race
conditions where you determine the port and then some other process
grabs it.
Something like:
def determineAvailablePort(host='localhost'):
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Set the first port to bind to, to the minimum port in the range.
for prt in range(16000, 16030):
try:
t.bind((host, prt))
except socket.error:
pass
else:
return skt, prt
raise Exception, 'No port in 16000:16030 available'
Where the caller uses the opened socket.
More information about the Python-list
mailing list