Determine if a port is in use/find next available free port

21 views
Skip to first unread message

Malcolm

unread,
Dec 14, 2009, 2:38:30 PM12/14/09
to cherrypy-users
Is there an OS independent way to determine is a specific port is in
use?

Scenario: I have a cherrypy based application running as a local
(desktop) server. I have the default port set to 8080, but if this
port is in use, I would like my server to detect this condition and
search for the next free port.

Does anyone have any techniques or code to share that would get me
started?

Thank you,
Malcolm

João Pinto

unread,
Dec 14, 2009, 3:59:03 PM12/14/09
to cherryp...@googlegroups.com


2009/12/14 Malcolm <webm...@awarepro.com>

--

You received this message because you are subscribed to the Google Groups "cherrypy-users" group.
To post to this group, send email to cherryp...@googlegroups.com.
To unsubscribe from this group, send email to cherrypy-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cherrypy-users?hl=en.



Hello you could use the socket module to probe for an available port:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   
port = 8080
while port < 9000:
    try:
        serversocket.bind(('localhost', port))
        # You may want: serversocket.bind((socket.gethostname(), port))
    except socket.error as e:
        if e.errno==98:
            port = port+1
        else:
            raise
    else:
        break
serversocket.close()
print "Found port", port

--
João Pinto
IRC: joaopinto @ irc.freenode.net
Jabber ID: lamego...@gmail.com
GetDeb Team Leader - http://www.getdeb.net

Malcolm

unread,
Dec 14, 2009, 7:44:21 PM12/14/09
to cherrypy-users
Hi João,

I'm running Python 2.6.4 (32-bit) on Windows 7 Pro (64-bit) and
received the following error when testing your code:

QUOTE: socket.error: [Errno 10048] Only one usage of each socket
address (protocol/network address/port) is normally permitted

I added errno 10048 to your exception handler and your code works
great.

UPDATED SNIPPET:

except socket.error as e:
if e.errno in ( 98, 10048 ):
print 'Port %s is unavailable (%s)' % ( port, e.errno )
port = port+1

Thank you very much for your code - it was a big help!

Regards,
Malcolm
Reply all
Reply to author
Forward
0 new messages