summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorSteve Kemp <steve@steve.org.uk>2012-11-20 09:59:46 +0000
committerSteve Kemp <steve@steve.org.uk>2012-11-20 09:59:46 +0000
commit4d75b213a155f66ce020ae152a201d67c4cf1171 (patch)
tree1f401881a73928ad52701156d61873f83e44ba0f /lib
parent2469580ace3f70eddb15d400bba8ce801ea4dbec (diff)
Added utility class.
Diffstat (limited to 'lib')
-rw-r--r--lib/custodian/dnsutil.rb72
1 files changed, 72 insertions, 0 deletions
diff --git a/lib/custodian/dnsutil.rb b/lib/custodian/dnsutil.rb
new file mode 100644
index 0000000..e42d5e3
--- /dev/null
+++ b/lib/custodian/dnsutil.rb
@@ -0,0 +1,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