Ruby过去常常使用Ping.pingecho方法,但似乎(和Ping模块)有时会消失: % rvm use 1.8.7Using ~/.rvm/gems/ruby-1.8.7-p334% ruby -rping -e 'p Ping.pingecho "127.0.0.1"'true% rvm use 1.9.2Using ~/.rvm/gems/ruby-1.9.2-p180% ruby -r
% 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 (LoadError) 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)
它移动到不同的库(所以我需要加载它吗?),或者
它已被删除,并替换为不同的模块(那么我应该用什么来确定IP是否可以访问?).
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