Module: FindAPort

Defined in:
lib/find_a_port.rb

Overview

Provides a utility to find an available TCP port on the local machine.

Class Method Summary collapse

Class Method Details

.available_portInteger

Returns an available port number on the local machine

This uses a hack where we create a TCPServer and allow Ruby to auto-bind an available port, ask for that port number, and then close the server. There is a small chance that something could bind to that port before you use it; this operation does nothing to reserve the port for you.

Returns:

  • (Integer)

    an available TCP port number



14
15
16
17
18
19
# File 'lib/find_a_port.rb', line 14

def available_port
  server = TCPServer.new('127.0.0.1', 0)
  server.addr[1]
ensure
  server.close if server
end