/tools/Ruby/lib/ruby/1.8/ping.rb

http://github.com/agross/netopenspace · Ruby · 64 lines · 23 code · 4 blank · 37 comment · 2 complexity · 8fbc38c5da9f1a06d4f388db2e84b2fa MD5 · raw file

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