Auto Selecting ports


#1

Hi, I’m trying to start up a WEBrick server on an unused port on my
system. On linux, I just tell it to use port 0, and I’m assigned an
open port. This doesn’t work on OS X for some reason. Does anyone have
a better way to do this? Here’s my test code:

require ‘webrick’

server = WEBrick::HTTPServer.new(
:Port => 0,
:DocumentRoot => Dir::pwd + “/htdocs”
)

puts “Using port: #{server[:Port]}”

trap(“INT”) { server.stop }
server.start

On linux, I get this:

[2006-03-18 15:56:25] INFO WEBrick 1.3.1
[2006-03-18 15:56:25] INFO ruby 1.8.4 (2005-12-24) [i386-linux]
Using port: 33278
[2006-03-18 15:56:25] INFO WEBrick::HTTPServer#start: pid=22031
port=33278

And I can connect to that port. On OS X, I get this:

[2006-03-18 15:56:21] INFO WEBrick 1.3.1
[2006-03-18 15:56:21] INFO ruby 1.8.2 (2004-12-25) [powerpc-darwin8.0]
Using port: 0
[2006-03-18 15:56:21] INFO WEBrick::HTTPServer#start: pid=14353 port=0

And I cannot connect to port 0. Does anyone have any suggestions for
me? I would appreciate any help I can get. Thanks!

–Aaron