https://github.com/yegor256/random-port
A Ruby gem to reserve a random TCP port, with a guarantee that it's not busy at the moment
https://github.com/yegor256/random-port
pool random-generation ruby ruby-gem rubygems tcp
Last synced: 9 months ago
JSON representation
A Ruby gem to reserve a random TCP port, with a guarantee that it's not busy at the moment
- Host: GitHub
- URL: https://github.com/yegor256/random-port
- Owner: yegor256
- License: mit
- Created: 2018-10-04T06:09:25.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2025-06-24T08:32:54.000Z (10 months ago)
- Last Synced: 2025-06-24T09:42:15.402Z (10 months ago)
- Topics: pool, random-generation, ruby, ruby-gem, rubygems, tcp
- Language: Ruby
- Homepage: https://rubygems.org/gems/random-port
- Size: 228 KB
- Stars: 16
- Watchers: 4
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Random TCP Port Generator for Ruby
[](https://www.rultor.com/p/yegor256/random-port)
[](https://www.jetbrains.com/ruby/)
[](https://github.com/yegor256/random-port/actions/workflows/rake.yml)
[](https://badge.fury.io/rb/random-port)
[](https://codeclimate.com/github/yegor256/random-port/maintainability)
[](https://rubydoc.info/github/yegor256/random-port/master/frames)
[](https://github.com/yegor256/random-port/blob/master/LICENSE.txt)
[](https://codecov.io/github/yegor256/random-port?branch=master)
[](https://hitsofcode.com/view/github/random-port/mailanes)
It's a simple Ruby gem to get a random TCP port.
First, install it:
```bash
gem install random-port
```
Then, use it like this, to reserve a random TCP port:
```ruby
require 'random-port'
port = RandomPort::Pool.new.acquire
```
The `Pool` guarantees that the port won't be used again. You can put
the port back to the pool after usage:
```ruby
RandomPort::Pool.new.acquire do |port|
# Use the TCP port. It will be returned back
# to the pool afterwards.
end
```
You can do it without the block:
```ruby
pool = RandomPort::Pool.new
port = pool.acquire
pool.release(port)
```
You can also use a pre-defined `Pool::SINGLETON` singleton:
```ruby
RandomPort::Pool::SINGLETON.acquire do |port|
# Use it here...
end
```
The pool is thread-safe by default.
You can configure it to be
not-thread-safe, using optional `sync` argument of the constructor.
## How to contribute
Read
[these guidelines](https://www.yegor256.com/2014/04/15/github-guidelines.html).
Make sure your build is green before you contribute
your pull request. You will need to have
[Ruby](https://www.ruby-lang.org/en/) 2.3+ and
[Bundler](https://bundler.io/) installed. Then:
```bash
bundle update
bundle exec rake
```
If it's clean and you don't see any error messages, submit your pull request.