Class: Net::TCPClient::Address

Inherits:
Object
  • Object
show all
Defined in:
lib/net/tcp_client/address.rb

Overview

Host name, ip address and port to connect to

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host_name, ip_address, port) ⇒ Address

Returns a new instance of Address.



47
48
49
50
51
# File 'lib/net/tcp_client/address.rb', line 47

def initialize(host_name, ip_address, port)
  @host_name  = host_name
  @ip_address = ip_address
  @port       = port.to_i
end

Instance Attribute Details

#host_nameObject

Returns the value of attribute host_name.



7
8
9
# File 'lib/net/tcp_client/address.rb', line 7

def host_name
  @host_name
end

#ip_addressObject

Returns the value of attribute ip_address.



7
8
9
# File 'lib/net/tcp_client/address.rb', line 7

def ip_address
  @ip_address
end

#portObject

Returns the value of attribute port.



7
8
9
# File 'lib/net/tcp_client/address.rb', line 7

def port
  @port
end

Class Method Details

.addresses(dns_name, port) ⇒ Object

Returns [Array<Net::TCPClient::Address>] addresses for a given DNS / host name. The Addresses will contain the resolved ip address, host name, and port number.

Note:

Multiple ip addresses will be returned when a DNS entry has multiple ip addresses associated with it.


24
25
26
# File 'lib/net/tcp_client/address.rb', line 24

def self.addresses(dns_name, port)
  ip_addresses(dns_name).collect { |ip| new(dns_name, ip, port) }
end

.addresses_for_server_name(server_name) ⇒ Object

Returns [Array<Net::TCPClient::Address>] addresses for a list of DNS / host name’s that are paired with their numbers

server_name should be either a host_name, or ip address combined with a port:

"host_name:1234"
"192.168.1.10:80"


34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/net/tcp_client/address.rb', line 34

def self.addresses_for_server_name(server_name)
  dns_name, port = server_name.split(":")
  port           = port.to_i
  unless dns_name && port&.positive?
    raise(
      ArgumentError,
      "Invalid host_name: #{server_name.inspect}. Must be formatted as 'host_name:1234' or '192.168.1.10:80'"
    )
  end

  addresses(dns_name, port)
end

.ip_addresses(dns_name) ⇒ Object

Returns [Array<String>] ip addresses for the supplied DNS entry Returns dns_name if it is already an IP Address



11
12
13
14
15
16
17
# File 'lib/net/tcp_client/address.rb', line 11

def self.ip_addresses(dns_name)
  ips = []
  Socket.getaddrinfo(dns_name, nil, Socket::AF_INET, Socket::SOCK_STREAM).each do |s|
    ips << s[3] if s[0] == "AF_INET"
  end
  ips.uniq
end

Instance Method Details

#to_sObject



53
54
55
# File 'lib/net/tcp_client/address.rb', line 53

def to_s
  "#{host_name}[#{ip_address}]:#{port}"
end