Class: TCPServer

Inherits:
Object show all
Defined in:
lib/rwd/net.rb

Class Method Summary collapse

Class Method Details

.freeport(from, to, remote = false) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/rwd/net.rb', line 31

def self.freeport(from, to, remote=false)
  if windows? or cygwin?
    TCPServer.freeport_windows(from, to, remote)
  else
    TCPServer.freeport_linux(from, to, remote)
  end
end

.freeport_linux(from, to, remote) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rwd/net.rb', line 39

def self.freeport_linux(from, to, remote)
  ports = (from..to).to_a
  port  = nil
  res   = nil

  while res.nil? and not ports.empty?
    begin
      port  = ports[0]
      ports.delete(port)

      io  = TCPServer.new(remote ? "0.0.0.0" : "localhost", port)

      res = [port, io]
    rescue
    end
  end

  res = [nil, nil]  if res.nil?

  port, io  = res

  return port, io
end

.freeport_windows(from, to, remote) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rwd/net.rb', line 63

def self.freeport_windows(from, to, remote)
  ports = (from..to).to_a
  port  = nil
  res   = nil

  while res.nil? and not ports.empty?
    begin
      port  = ports.any
      ports.delete(port)

      io  = TCPSocket.new("localhost", port)
      io.close
    rescue
      res = port
    end
  end

  port, io  = res

  return port, io
end

.freeport_windows2(from, to, remote) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/rwd/net.rb', line 85

def self.freeport_windows2(from, to, remote)
  res = nil
  port  = from

  while res.nil? and port <= to
    begin
      io  = TCPSocket.new("localhost", port)
      io.close

      port += 1
    rescue
      res = port
    end
  end

  return res
end

.usedports(from, to) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/rwd/net.rb', line 103

def self.usedports(from, to)
  threads = []
  res   = []

  from.upto(to) do |port|
    threads << Thread.new do
      begin
        io  = TCPSocket.new("localhost", port)
        io.close

        port
      rescue
        nil
      end
    end
  end

  threads.each do |thread|
    port  = thread.value
    res << port unless port.nil?
  end

  return res
end