detecting socket in use on localhost

Berends j at jochem.{N0SP4M}.tv
Mon Oct 4 12:34:08 CEST 2004


Alex Martelli wrote:
> Berends <j at jochem.{N0SP4M}.tv> wrote:

> Oh yes, an unstated corollary of my 'If' above was: if you don't care
> about cross-platform portability AND are using a good platform, then
> there are no doubt better solutions!

_I_ use a good platform, but my boss wants me to make it x-platform ;)

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]



More information about the Python-list mailing list