Class: Net::Ping::External

Inherits:
Net::Ping show all
Defined in:
lib/net/ping/external.rb

Constant Summary

Constants inherited from Net::Ping

VERSION

Instance Attribute Summary

Attributes inherited from Net::Ping

#duration, #exception, #host, #port, #timeout, #warning

Instance Method Summary collapse

Methods inherited from Net::Ping

#initialize

Constructor Details

This class inherits a constructor from Net::Ping

Instance Method Details

#ping(host = @host) ⇒ Object Also known as: ping?, pingecho

Pings the host using your system’s ping utility and checks for any errors or warnings. Returns true if boolful, or false if not.

If false, then the Ping::External#exception method should contain a string indicating what went wrong. If true, the Ping::External#warning method may or may not contain a value.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/net/ping/external.rb', line 14

def ping(host = @host)
   super(host)
   input, output, error = ""
   pstring = "ping "
   bool = false
   
   case RUBY_PLATFORM
      when /linux|bsd/i
         pstring += "-c 1 #{host}"
      when /solaris|sunos/i
         pstring += "#{host} 1"
      when /hpux/i
         pstring += "#{host} -n 1"
      when /win32|windows|mswin/i
         pstring += "-n 1 #{host}"
      else
         pstring += "#{host}"
   end
   
   if RUBY_PLATFORM.match('mswin')
      require 'win32/open3'
   else
      require 'open3'            
   end

   start_time = Time.now
   
   Timeout.timeout(@timeout){
      input, output, error = Open3.popen3(pstring)
   }

   e = error.gets # Can't chomp yet, might be nil

   input.close
   error.close
  
   unless e.nil?
      if e =~ /warning/i
         @warning = e.chomp
         bool = true
      else
         @exception = e.chomp
      end
   # The "no answer" response goes to stdout, not stderr, so check it
   else
      lines = output.readlines
      output.close
      if lines.nil? || lines.empty?
         bool = true
      else
         regexp = /
            no\ answer|
            host\ unreachable|
            could\ not\ find\ host|
            request\ timed\ out
         /ix
         lines.each{ |e|
            if regexp.match(e)
               @exception = e.chomp
               break
            end
         }
         bool = true unless @exception
      end
   end

   # There is no duration if the ping failed
   @duration = Time.now - start_time if bool

   bool
end