简体   繁体   中英

How do you find a random open port in 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?

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.

You can try random-port , a simple Ruby gem (I'm the author):

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

The best way, though, is to use the block:

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

The pool is thread-safe and guarantees that the port won't be used by another thread or anywhere else in the app, until it's released.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM