summaryrefslogtreecommitdiff
path: root/lib/custodian/dnsutil.rb
blob: e42d5e324730d09ba3d3fcf40c682c75b9675a36 (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
require 'ipaddr'
require 'socket'
require 'timeout'



#
#  This class is responsible for doing forward/reverse DNS lookups
#
class DNSUtil


  #
  # Return the reverse DNS for the specified IP address, nil on failure.
  #
  def DNSUtil.ip_to_hostname( ip )
    resolved = nil
    begin
      timeout( 4 ) do
        begin
          Socket.getaddrinfo(ip, 'echo').each do |a|
            resolved = a[2] if ( a )
          end
        rescue SocketError
          resolved = nil
        end
      end
    rescue Timeout::Error => e
      resolved = nil
    end
    resolved
  end


  #
  # Convert a hostname to an IP address, return nil on failure.
  #
  def DNSUtil.hostname_to_ip( hostname )

    resolved = nil

    begin
      timeout( 4 ) do
        begin
          Socket.getaddrinfo(hostname, 'echo').each do |a|
            resolved = a[3] if ( a )
          end
        rescue SocketError
          resolved = nil
        end
      end
    rescue Timeout::Error => e
      resolved = nil
    end
    resolved
  end

end


if __FILE__ == $0 then

  %w( ssh.steve.org.uk ipv6.steve.org.uk ).each do |name|
    puts "Hostname test: #{name} #{DNSUtil.hostname_to_ip(name) }"
  end

  %w( 80.68.85.46 80.68.85.48 2001:41c8:125:46::22 ).each do |name|
    puts "Hostname test: #{name} #{DNSUtil.ip_to_hostname(name) }"
  end
end