1998-01-16 15:13:05 +03:00
|
|
|
#
|
2006-10-09 18:49:49 +04:00
|
|
|
# = ping.rb: Check a host for upness
|
|
|
|
#
|
|
|
|
# Author:: Yukihiro Matsumoto
|
|
|
|
# Documentation:: Konrad Meyer
|
|
|
|
#
|
|
|
|
# Performs the function of the basic network testing tool, ping.
|
|
|
|
# See: Ping.
|
1998-01-16 15:13:05 +03:00
|
|
|
#
|
2006-08-04 22:05:50 +04:00
|
|
|
|
|
|
|
require 'timeout'
|
|
|
|
require "socket"
|
|
|
|
|
2006-10-09 18:49:49 +04:00
|
|
|
#
|
|
|
|
# Ping contains routines to test for the reachability of remote hosts.
|
|
|
|
# Currently the only routine implemented is pingecho().
|
1998-01-16 15:13:05 +03:00
|
|
|
#
|
2006-10-09 18:49:49 +04:00
|
|
|
# Ping.pingecho uses a TCP echo (not an ICMP echo) to determine if the
|
1998-01-16 15:13:05 +03:00
|
|
|
# remote host is reachable. This is usually adequate to tell that a remote
|
2006-10-09 18:49:49 +04:00
|
|
|
# host is available to telnet, ftp, or ssh to.
|
|
|
|
#
|
|
|
|
# Warning: Ping.pingecho may block for a long time if DNS resolution is
|
|
|
|
# slow. Requiring 'resolv-replace' allows non-blocking name resolution.
|
1999-01-20 07:59:39 +03:00
|
|
|
#
|
2006-10-09 18:49:49 +04:00
|
|
|
# Usage:
|
|
|
|
#
|
|
|
|
# require 'ping'
|
1998-01-16 15:13:05 +03:00
|
|
|
#
|
2006-10-09 18:49:49 +04:00
|
|
|
# puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10)
|
1998-01-16 15:13:05 +03:00
|
|
|
#
|
|
|
|
module Ping
|
2006-08-04 22:05:50 +04:00
|
|
|
|
2006-10-09 18:49:49 +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.
|
|
|
|
#
|
|
|
|
# Example:
|
|
|
|
#
|
|
|
|
# require 'ping'
|
|
|
|
#
|
|
|
|
# Ping.pingecho "google.com", 10, 80
|
|
|
|
#
|
1999-01-20 07:59:39 +03:00
|
|
|
def pingecho(host, timeout=5, service="echo")
|
1998-01-16 15:13:05 +03:00
|
|
|
begin
|
1999-01-20 07:59:39 +03:00
|
|
|
timeout(timeout) do
|
2002-07-11 12:22:18 +04:00
|
|
|
s = TCPSocket.new(host, service)
|
1999-01-20 07:59:39 +03:00
|
|
|
s.close
|
|
|
|
end
|
2001-02-15 09:01:00 +03:00
|
|
|
rescue Errno::ECONNREFUSED
|
|
|
|
return true
|
2005-08-01 20:42:48 +04:00
|
|
|
rescue Timeout::Error, StandardError
|
1999-01-20 07:59:39 +03:00
|
|
|
return false
|
1998-01-16 15:13:05 +03:00
|
|
|
end
|
1999-01-20 07:59:39 +03:00
|
|
|
return true
|
1998-01-16 15:13:05 +03:00
|
|
|
end
|
1999-01-20 07:59:39 +03: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 15:13:05 +03:00
|
|
|
end
|