Module: Nodule::Util

Defined in:
lib/nodule/util.rb

Class Method Summary collapse

Class Method Details

._random_port(max_tries = 500) {|Fixnum| ... } ⇒ Fixnum

Try random ports > 10_000 looking for one that’s free.

Parameters:

  • max (Fixnum)

    number of tries to find a free port

Yields:

  • (Fixnum)

    port

Returns:

  • (Fixnum)

    port number



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/nodule/util.rb', line 27

def self._random_port(max_tries=500)
  tries = 0

  while tries < max_tries
    port = random_port
    next if @seen.has_key? port

    socket = begin
      yield port
    rescue Errno::EADDRINUSE
      @seen[port] = true
      tries += 1
      next
    end

    socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
    socket.close
    return port
  end
end

.random_portFixnum

Return a random integer between 10_000 and 65_534

Returns:

  • (Fixnum)


52
53
54
# File 'lib/nodule/util.rb', line 52

def self.random_port
  rand(55534) + 10_000
end

.random_tcp_port(max_tries = 500) ⇒ Object



7
8
9
10
11
# File 'lib/nodule/util.rb', line 7

def self.random_tcp_port(max_tries=500)
  self._random_port do |port|
    TCPServer.new port
  end
end

.random_udp_port(max_tries = 500) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/nodule/util.rb', line 13

def self.random_udp_port(max_tries=500)
  self._random_port do |port|
    socket = UDPSocket.new
    socket.bind("0.0.0.0", port)
    socket
  end
end