blob: b498f137ab5f34ffd10ee9a01837e35a7c7a0cfe (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
require 'getoptlong'
require 'socket'
require 'timeout'
#
# This class has methods to determine whether the target
# of a hostname/IP address is IPv4 or IPv6.
#
# Assuming the address resolves to one of those two types
# it can invoke on of /usr/bin/ping or /usr/bin/ping6 appropriately.
#
class MultiPing
#
# The hostname we'll ping, and the resolved address.
#
attr_reader :hostname, :resolved
#
# Save the hostname away, resolve it if possible.
#
def initialize( hostname )
@hostname = hostname
@resolved = resolve_hostname( hostname )
end
#
# TODO: Use custodian/dnsutil now it exists.
#
def resolve_hostname( hostname )
res = nil
begin
timeout( 4 ) do
begin
Socket.getaddrinfo(hostname, 'echo').each do |a|
res = a[3]
end
rescue SocketError
end
end
rescue Timeout::Error => e
resolved = nil
end
res
end
#
# Return the resolved address
#
def address
@resolved
end
#
# Does the hostname resolve to an IPv4 address?
#
def is_ipv4?
if ( ( ! @resolved.nil? ) && ( @resolved =~ /^([0-9]+).([0-9]+).([0-9]+).([0-9]+)$/ ) )
true
else
false
end
end
#
# Does the hostname resolve to an IPv6 address?
#
def is_ipv6?
if ( ( ! @resolved.nil? ) && ( @resolved =~ /^([a-f0-9:]+)$/i ) )
true
else
false
end
end
#
# Run the ping - if it succeeds return "true".
#
# Return false on error.
#
def run_ping
if ( is_ipv6? )
if ( system( "ping6 -c 1 #{@resolved} 2>/dev/null >/dev/null" ) == true )
return true
end
elsif( is_ipv4? )
if ( system( "ping -c 1 #{@resolved} 2>/dev/null >/dev/null" ) == true )
return true
end
else
puts "ERROR: Resolved to neither an IPv6 or IPv4 address."
end
return false
end
end
|