Class: NetworkUtils::Port
- Inherits:
-
Object
- Object
- NetworkUtils::Port
- Defined in:
- lib/network_utils/port.rb
Overview
Simple class to work with ports Allows to get random port number, check availability, etc.
Constant Summary collapse
- PORT_LOOKUP_RETRY_LIMIT =
The max limit for port lookup retries
50- IANA_PORT_RANGE =
Internet Assigned Numbers Authority suggested range
(49_152..65_535).freeze
Class Method Summary collapse
-
.available?(port, host = '127.0.0.1', timeout = 1) ⇒ Boolean
(also: free?)
Checks if the port is available (free) on the host.
-
.opened?(port, host = '127.0.0.1', timeout = 1) ⇒ Boolean
(also: occupied?)
Checks if the port is opened (occupied / being listened) on the host.
-
.random ⇒ Boolean
Generates random port from IANA recommended range.
-
.random_free ⇒ Boolean
Generates random port from IANA recommended range which is free on the localhost.
Class Method Details
.available?(port, host = '127.0.0.1', timeout = 1) ⇒ Boolean Also known as: free?
Checks if the port is available (free) on the host
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/network_utils/port.rb', line 33 def self.available?(port, host = '127.0.0.1', timeout = 1) return false unless port && host && timeout && timeout.positive? Timeout.timeout(timeout) do TCPSocket.new(host, port).close false end rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH true rescue SocketError, Timeout::Error, Errno::EADDRNOTAVAIL false end |
.opened?(port, host = '127.0.0.1', timeout = 1) ⇒ Boolean Also known as: occupied?
Just the opposite of ‘available?`
Checks if the port is opened (occupied / being listened) on the host
61 62 63 |
# File 'lib/network_utils/port.rb', line 61 def self.opened?(port, host = '127.0.0.1', timeout = 1) !available?(port, host, timeout) end |
.random ⇒ Boolean
The Internet Assigned Numbers Authority (IANA) suggests the range 49152 to 65535 (215+214 to 216−1) for dynamic or private ports.
Generates random port from IANA recommended range
72 73 74 |
# File 'lib/network_utils/port.rb', line 72 def self.random rand(IANA_PORT_RANGE) end |
.random_free ⇒ Boolean
The Internet Assigned Numbers Authority (IANA) suggests the range 49152 to 65535 (215+214 to 216−1) for dynamic or private ports.
Generates random port from IANA recommended range which is free on the localhost
83 84 85 86 87 88 89 90 |
# File 'lib/network_utils/port.rb', line 83 def self.random_free PORT_LOOKUP_RETRY_LIMIT.times do port = random return port if available?(port) end nil end |