lib/ping.rb


DEFINITIONS

This source file includes following functions.


   1  #
   2  # ping.rb -- check a host for upness
   3  #
   4  #= SYNOPSIS
   5  #
   6  #   require 'ping'
   7  #    print "'jimmy' is alive and kicking\n" if Ping.pingecho('jimmy', 10) ;
   8  #
   9  #= DESCRIPTION
  10  #
  11  # This module contains routines to test for the reachability of remote hosts.
  12  # Currently the only routine implemented is pingecho(). 
  13  #
  14  # pingecho() uses a TCP echo (I<not> an ICMP one) to determine if the
  15  # remote host is reachable. This is usually adequate to tell that a remote
  16  # host is available to rsh(1), ftp(1), or telnet(1) onto.
  17  #
  18  #== Parameters
  19  #
  20  #  : hostname
  21  #
  22  #    The remote host to check, specified either as a hostname or as an
  23  #    IP address.
  24  #
  25  #  : timeout
  26  #
  27  #    The timeout in seconds. If not specified it will default to 5 seconds.
  28  #
  29  #  : service
  30  #
  31  #    The service port to connect.  The default is "echo".
  32  #
  33  #= WARNING
  34  #
  35  # pingecho() uses user-level thread to implement the timeout, so it may block
  36  # for long period if named does not respond for some reason.
  37  #
  38  #=end
  39  
  40  require 'timeout'
  41  require "socket"
  42  
  43  module Ping
  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
  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