How to tell Cherrypy to use any available port?

30 views
Skip to first unread message

Sebastian Rahlf

unread,
Feb 11, 2012, 4:46:28 AM2/11/12
to cherrypy-users
Hello!

This has been asked before but I could not find a satifying answer.

I want to use CherryPy in a test suite. It will always run on
localhost but I have no chance of knowing which ports will be
available beforehand as there may already be another instance started
by another test.

The way I went about this previously was to bind to ('127.0.0.1', 0)
which would guarantee an open port to be used. How would I do this
with CherryPy? Using module random, as previously suggested, is not an
option for me.

Thanks for any pointers!

Seb.

Daniel Bryan

unread,
Feb 11, 2012, 7:10:43 AM2/11/12
to cherryp...@googlegroups.com
Being a total cherrypy amateur I'm sure the community will have a much better suggestion than me, but perhaps during your server startup you could create simple socket connections, wrapped in a try/except, and iterate through a range of acceptable port numbers until you get one that's available (and which you have permission for)? Something like this..

import socket

def find_port(acceptable_ports):
port = acceptable_ports.pop()
while port in acceptable_ports:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serversocket.bind((socket.gethostname(), port))
return port
except socket.error:
port = acceptable_ports.pop()
raise IOError('No available ports in your range sucked in')
port = find_port(range(1,80))

Goes without saying that this is ad hoc, ugly, probably breaks a whole bunch of import principles of network programming and good process behaviour. I'm sure there's some way to do this in a single line. 


--
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.


Daniel Bryan

unread,
Feb 11, 2012, 7:13:26 AM2/11/12
to cherryp...@googlegroups.com
Oh, my while loop there is fundamentally broken. Joy! This is what you get for answering list questions after months of no Python -___-
Reply all
Reply to author
Forward
0 new messages