1 | #
|
---|
2 | # = ping.rb: Check a host for upness
|
---|
3 | #
|
---|
4 | # Author:: Yukihiro Matsumoto
|
---|
5 | # Documentation:: Konrad Meyer
|
---|
6 | #
|
---|
7 | # Performs the function of the basic network testing tool, ping.
|
---|
8 | # See: Ping.
|
---|
9 | #
|
---|
10 |
|
---|
11 | require 'timeout'
|
---|
12 | require "socket"
|
---|
13 |
|
---|
14 | #
|
---|
15 | # Ping contains routines to test for the reachability of remote hosts.
|
---|
16 | # Currently the only routine implemented is pingecho().
|
---|
17 | #
|
---|
18 | # Ping.pingecho uses a TCP echo (not an ICMP echo) to determine if the
|
---|
19 | # remote host is reachable. This is usually adequate to tell that a remote
|
---|
20 | # host is available to telnet, ftp, or ssh to.
|
---|
21 | #
|
---|
22 | # Warning: Ping.pingecho may block for a long time if DNS resolution is
|
---|
23 | # slow. Requiring 'resolv-replace' allows non-blocking name resolution.
|
---|
24 | #
|
---|
25 | # Usage:
|
---|
26 | #
|
---|
27 | # require 'ping'
|
---|
28 | #
|
---|
29 | # puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10)
|
---|
30 | #
|
---|
31 | module Ping
|
---|
32 |
|
---|
33 | #
|
---|
34 | # Return true if we can open a connection to the hostname or IP address
|
---|
35 | # +host+ on port +service+ (which defaults to the "echo" port) waiting up
|
---|
36 | # to +timeout+ seconds.
|
---|
37 | #
|
---|
38 | # Example:
|
---|
39 | #
|
---|
40 | # require 'ping'
|
---|
41 | #
|
---|
42 | # Ping.pingecho "google.com", 10, 80
|
---|
43 | #
|
---|
44 | def pingecho(host, timeout=5, service="echo")
|
---|
45 | begin
|
---|
46 | timeout(timeout) do
|
---|
47 | s = TCPSocket.new(host, service)
|
---|
48 | s.close
|
---|
49 | end
|
---|
50 | rescue Errno::ECONNREFUSED
|
---|
51 | return true
|
---|
52 | rescue Timeout::Error, StandardError
|
---|
53 | return false
|
---|
54 | end
|
---|
55 | return true
|
---|
56 | end
|
---|
57 | module_function :pingecho
|
---|
58 | end
|
---|
59 |
|
---|
60 | if $0 == __FILE__
|
---|
61 | host = ARGV[0]
|
---|
62 | host ||= "localhost"
|
---|
63 | printf("%s alive? - %s\n", host, Ping::pingecho(host, 5))
|
---|
64 | end
|
---|