Ruby: Ping.pingecho missing
Ruby used to have a Ping.pingecho
method, but it seems as if (and the Ping
module) have disappeared sometime:
% rvm use 1.8.7
Using ~/.rvm/gems/ruby-1.8.7-p334
% ruby -rping -e 'p Ping.pingecho "127.0.0.1"'
true
% rvm use 1.9.2
Using ~/.rvm/gems/ruby-1.9.2-p180
% ruby -rping -e 'p Ping.pingecho "127.0.0.1"'
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- ping (Load开发者_C百科Error)
from <internal:lib/rubygems/custom_require>:29:in `require'
% ruby -e 'p Ping.pingecho "127.0.0.1"'
-e:1:in `<main>': uninitialized constant Object::Ping (NameError)
Has it moved to a different library (so what should I require
to load it?), or
has it been deleted, and replaced with a different module (so what should I use to determine whether a IP is reachable?).
Don know why or where it has gone. Rails still has a Ping class. A slight adaptation (to use a class method) would be:
require 'timeout'
require 'socket'
class Ping
def self.pingecho(host, timeout=5, service="echo")
begin
timeout(timeout) do
s = TCPSocket.new(host, service)
s.close
end
rescue Errno::ECONNREFUSED
return true
rescue Timeout::Error, StandardError
return false
end
return true
end
end
p Ping.pingecho("127.0.0.1") #=> true
p Ping.pingecho("localhost") #=> true
I just encountered this issue. I settled with the net-ping gem as a replacement. It has a clear TCP ping example in gems/net-ping-1.7.7/examples/example_pingtcp.rb:
p1 = Net::Ping::TCP.new(good, 'http')
p p1.ping?
The rubydoc.info link at the time of this writing is not working, but here is a useful comment in the source of the module (tcp.rb)
# This method attempts to ping a host and port using a TCPSocket with
# the host, port and timeout values passed in the constructor. Returns
# true if successful, or false otherwise.
So I swapped this:
return Ping.pingecho(server, 5, 22)
With this:
p = Net::Ping::TCP.new(server, 22, 5)
p.ping?
There are two caveats in moving from the old to the new equivalent module:
- The arguments to the constructor are reversed (port and timeout)
- The actual invocation of a ping is accomplished by calling the
ping?
method, rather than just instantiating.
精彩评论