Class: Net::Ping::External

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

Overview

The Ping::External class encapsulates methods for external (system) pings.

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 successful, or false if not.

If the ping failed then the Ping::External#exception method should contain a string indicating what went wrong. If the ping succeeded then the Ping::External#warning method may or may not contain a value.



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
# File 'lib/net/ping/external.rb', line 18

def ping(host = @host)
  super(host)

  pcmd = ['ping']
  bool = false

  case RbConfig::CONFIG['host_os']
    when /linux|bsd|osx|mach|darwin/i
      pcmd += ['-c1', host]
    when /solaris|sunos/i
      pcmd += [host, '1']
    when /hpux/i
      pcmd += [host, '-n1']
    when /win32|windows|msdos|mswin|cygwin|mingw/i
      pcmd += ['-n', '1', host]
    else
      pcmd += [host]
  end

  start_time = Time.now

  begin
    err = nil

    Timeout.timeout(@timeout){
      Open3.popen3(*pcmd) do |stdin, stdout, stderr, thread|
        err = stderr.gets # Can't chomp yet, might be nil

        case thread.value.exitstatus
          when 0
            bool = true  # Success, at least one response.
            if err & err =~ /warning/i
              @warning = err.chomp
            end
          when 2
            bool = false # Transmission successful, no response.
            @exception = err.chomp
          else
            bool = false # An error occurred
            @exception = err.chomp
        end
      end
    }
  rescue Exception => error
    @exception = error.message
  end

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

  bool
end