1998-01-16 07:13:05 -05:00
|
|
|
#
|
|
|
|
# ping.rb -- check a host for upness
|
|
|
|
#
|
2006-08-04 14:05:50 -04:00
|
|
|
|
|
|
|
require 'timeout'
|
|
|
|
require "socket"
|
|
|
|
|
1998-01-16 07:13:05 -05:00
|
|
|
#= SYNOPSIS
|
|
|
|
#
|
|
|
|
# require 'ping'
|
2006-08-04 14:05:50 -04:00
|
|
|
#
|
|
|
|
# puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10)
|
1998-01-16 07:13:05 -05:00
|
|
|
#
|
|
|
|
#= DESCRIPTION
|
|
|
|
#
|
|
|
|
# This module contains routines to test for the reachability of remote hosts.
|
|
|
|
# Currently the only routine implemented is pingecho().
|
|
|
|
#
|
2006-08-04 14:05:50 -04:00
|
|
|
# pingecho() uses a TCP echo (_not_ an ICMP echo) to determine if the
|
1998-01-16 07:13:05 -05:00
|
|
|
# remote host is reachable. This is usually adequate to tell that a remote
|
2006-08-04 14:05:50 -04:00
|
|
|
# host is available to rsh(1), ftp(1), or telnet(1) to.
|
1999-01-19 23:59:39 -05:00
|
|
|
#
|
1998-01-16 07:13:05 -05:00
|
|
|
#= WARNING
|
|
|
|
#
|
2006-08-04 14:05:50 -04:00
|
|
|
# pingecho() may block for a long period if name resolution is slow. Require
|
|
|
|
# 'resolv-replace' to use non-blocking name resolution.
|
1998-01-16 07:13:05 -05:00
|
|
|
#
|
|
|
|
module Ping
|
2006-08-04 14:05:50 -04:00
|
|
|
|
|
|
|
# return true if we can open a connection to the hostname or IP address
|
|
|
|
# +host+ on port +service+ (which defaults to the "echo" port) waiting up to
|
|
|
|
# +timeout+ seconds.
|
1999-01-19 23:59:39 -05:00
|
|
|
def pingecho(host, timeout=5, service="echo")
|
1998-01-16 07:13:05 -05:00
|
|
|
begin
|
1999-01-19 23:59:39 -05:00
|
|
|
timeout(timeout) do
|
2002-07-11 04:22:18 -04:00
|
|
|
s = TCPSocket.new(host, service)
|
1999-01-19 23:59:39 -05:00
|
|
|
s.close
|
|
|
|
end
|
2001-02-15 01:01:00 -05:00
|
|
|
rescue Errno::ECONNREFUSED
|
|
|
|
return true
|
2005-08-01 12:42:48 -04:00
|
|
|
rescue Timeout::Error, StandardError
|
1999-01-19 23:59:39 -05:00
|
|
|
return false
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
1999-01-19 23:59:39 -05:00
|
|
|
return true
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
1999-01-19 23:59:39 -05:00
|
|
|
module_function :pingecho
|
|
|
|
end
|
|
|
|
|
|
|
|
if $0 == __FILE__
|
|
|
|
host = ARGV[0]
|
|
|
|
host ||= "localhost"
|
|
|
|
printf("%s alive? - %s\n", host, Ping::pingecho(host, 5))
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|