Module: Freeport

Defined in:
lib/freeport.rb,
lib/freeport/version.rb

Defined Under Namespace

Classes: OutOfPorts

Constant Summary collapse

PORT_START =
(2<<9)+1
PORT_END =
(2<<15)-1
PORT_RANGE =
PORT_END-PORT_START
LOCALHOST =
'127.0.0.1'
VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.availableObject Also known as: a



24
25
26
# File 'lib/freeport.rb', line 24

def available
  ports.size
end

.portObject Also known as: p



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/freeport.rb', line 12

def port
  2.times do |try|
    ports.empty? and try==0 and @ports = (PORT_START..PORT_END).to_a
    until ports.empty?
      port = ports.sample
      ports.delete(port)
      return port if useable port
    end
  end
  raise Freeport::OutOfPorts if try > 0
end

.useable(port) ⇒ Object Also known as: u



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/freeport.rb', line 28

def useable port
  begin
    Timeout::timeout(2) do
      begin
        TCPSocket.new(LOCALHOST,port).close
        false
      rescue Errno::ECONNREFUSED
        true
      end
    end
  rescue Timeout::Error
    true
  end
end