2011-09-22 90 views
3

紅寶石曾經有一個Ping.pingecho方法,但它好像(和Ping模塊)已經消失一段時間:紅寶石:Ping.pingecho缺少

% 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) 

已經把它移到一個不同的庫(那麼應該怎麼我require加載它?),或 它已被刪除,並替換爲一個不同的模塊(所以我應該使用什麼來確定IP是否可達?)。

回答

4

不知道爲什麼或去哪裏。 Rails仍然有一個Ping類。稍微適應(使用類方法)將是:

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 
2

我剛剛遇到此問題。我以net-ping作爲替代品解決了問題。它在寶石清晰的TCP平例如/淨平-1.7.7 /例子/ example_pingtcp.rb:

p1 = Net::Ping::TCP.new(good, 'http') 
p p1.ping? 

rubydoc.info link在寫這篇文章的時候不工作,但這裏是一個有用的評論模塊的源(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. 

所以我交換這樣的:

return Ping.pingecho(server, 5, 22) 

利用該:

p = Net::Ping::TCP.new(server, 22, 5) 
p.ping? 

有兩點需要說明從舊移動到新的等效模塊:

  1. 構造函數的參數被顛倒
  2. 一平的實際調用是通過調用來完成(端口和超時)方法,而不僅僅是實例化。