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.
精彩评论