1998-01-16 07:13:05 -05:00
|
|
|
#
|
|
|
|
# ping.rb -- check a host for upness
|
|
|
|
#
|
|
|
|
#= SYNOPSIS
|
|
|
|
#
|
|
|
|
# require 'ping'
|
|
|
|
# print "'jimmy' is alive and kicking\n" if Ping.pingecho('jimmy', 10) ;
|
|
|
|
#
|
|
|
|
#= DESCRIPTION
|
|
|
|
#
|
|
|
|
# This module contains routines to test for the reachability of remote hosts.
|
|
|
|
# Currently the only routine implemented is pingecho().
|
|
|
|
#
|
|
|
|
# pingecho() uses a TCP echo (I<not> an ICMP one) to determine if the
|
|
|
|
# remote host is reachable. This is usually adequate to tell that a remote
|
|
|
|
# host is available to rsh(1), ftp(1), or telnet(1) onto.
|
|
|
|
#
|
|
|
|
#== Parameters
|
|
|
|
#
|
|
|
|
# : hostname
|
|
|
|
#
|
|
|
|
# The remote host to check, specified either as a hostname or as an
|
|
|
|
# IP address.
|
|
|
|
#
|
|
|
|
# : timeout
|
|
|
|
#
|
|
|
|
# The timeout in seconds. If not specified it will default to 5 seconds.
|
|
|
|
#
|
1999-01-19 23:59:39 -05:00
|
|
|
# : service
|
|
|
|
#
|
|
|
|
# The service port to connect. The default is "echo".
|
|
|
|
#
|
1998-01-16 07:13:05 -05:00
|
|
|
#= WARNING
|
|
|
|
#
|
|
|
|
# pingecho() uses user-level thread to implement the timeout, so it may block
|
|
|
|
# for long period if named does not respond for some reason.
|
|
|
|
#
|
|
|
|
#=end
|
|
|
|
|
1999-01-19 23:59:39 -05:00
|
|
|
require 'timeout'
|
2000-07-18 02:00:45 -04:00
|
|
|
require "socket"
|
1999-01-19 23:59:39 -05:00
|
|
|
|
1998-01-16 07:13:05 -05:00
|
|
|
module Ping
|
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
|
2004-07-24 05:48:21 -04:00
|
|
|
rescue Timeout::Error
|
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
|