How to find a random open port in Ruby?

If you call DRb.start_service(nil, some_obj), then DRb.uriyou return the local URI, including the port number that another process can use to make calls.

I just want some code to find a random available port and return that port number instead of starting a full service DRb. Is there an easy way to do this in Ruby?

+4
source share
2 answers

Not tried, but it might work.

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

A process may allow the system to automatically assign a port. For
both the Internet domain and the XNS domain, specifying port number 0 before calling bind () asks for this.

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

0 socket.bind. local_address .

+18

random-port, Ruby ( ):

require 'random-port'
port = RandomPort::Pool.new.acquire

:

RandomPort::Pool.new.acquire do |port|
  # Use the port, it will be returned back
  # to the pool afterward.
end

- , - , .

+1

All Articles