Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find a random open port in Ruby?

Tags:

ruby

If you call DRb.start_service(nil, some_obj) and then DRb.uri, you get back the local URI, including a port number, that another process can use to make calls.

I'm looking to just have some code find a random available port and return that port number, instead of starting up a full-fledged DRb service. Is there a simple way to do this in Ruby?

like image 709
dan Avatar asked Nov 30 '22 04:11

dan


1 Answers

Haven't tried it, but this may work.

From http://wiki.tcl.tk/2230

The process can let the system automatically assign a port. For
both the Internet domain and the XNS domain, specifying a port number of 0 before calling bind() requests the system to do this.

Also see http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/classes/Socket.html#M003723

 require 'socket'

 # use Addrinfo
 socket = Socket.new(:INET, :STREAM, 0)
 socket.bind(Addrinfo.tcp("127.0.0.1", 0))
 p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>

Note the use port 0 in socket.bind call. Expected behavior is the local_address will contain the random open port.

like image 131
Steve Wilhelm Avatar answered Dec 18 '22 15:12

Steve Wilhelm