Module: Corgibytes::Freshli::Commons::Ports

Defined in:
lib/corgibytes/freshli/commons/ports.rb

Overview

Contains utility methods for working with IP ports, specifically determining which ones are available for use.

Class Method Summary collapse

Class Method Details

.attempt_connection(port) ⇒ Object

rubocop:enable Metrics/MethodLength



27
28
29
30
31
32
33
# File 'lib/corgibytes/freshli/commons/ports.rb', line 27

def self.attempt_connection(port)
  # based on https://stackoverflow.com/a/34375147/243215
  require 'socket'
  socket = Socket.new(Socket::Constants::AF_INET, Socket::Constants::SOCK_STREAM, 0)
  socket.bind(Socket.pack_sockaddr_in(port, '0.0.0.0'))
  socket.close
end

.available?(port) ⇒ Boolean

rubocop:disable Metrics/MethodLength

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/corgibytes/freshli/commons/ports.rb', line 9

def self.available?(port)
  max_attempts = 1000
  attempts = 0
  begin
    attempts += 1
    yield(attempts) if block_given?
    attempt_connection(port)
    true
  rescue Errno::EADDRINUSE
    if attempts < max_attempts
      sleep 0.1
      retry
    end
    false
  end
end