It's a simple Ruby gem to get a random TCP port.
First, install it:
gem install random-portThen, use it like this, to reserve a random TCP port:
require 'random-port'
port = RandomPort::Pool.new.acquireThe Pool guarantees that the port isn't used again.
You can put the port back to the pool after usage:
RandomPort::Pool.new.acquire do |port|
# Use the TCP port. It will be returned back
# to the pool afterwards.
endYou can do it without the block:
pool = RandomPort::Pool.new
port = pool.acquire
pool.release(port)You can also use a pre-defined Pool::SINGLETON singleton:
RandomPort::Pool::SINGLETON.acquire do |port|
# Use it here...
endOr use shortened version, all methods called in RandomPort
are delegated to Pool::SINGLETON:
RandomPort.acquire do |port|
# Use it here...
endThe pool is thread-safe by default.
You can configure it to be not-thread-safe,
using optional sync argument of the constructor.
Read these guidelines. Make sure your build is green before you contribute your pull request. You need to have Ruby 3.3+ and Bundler installed. Then:
bundle update
bundle exec rakeIf it's clean and you don't see any error messages, submit your pull request.