tags:

views:

44

answers:

2

I want to ping a site in my ruby code and saw that net-ping was a nice library to do this with. Unfortunately, when I tried to gem install net-ping I got the following error:

C:>gem install net-ping ERROR: Error installing net-ping: win32-open3 requires Ruby version < 1.9.0.

upon further research, I found that net-ping was not available yet for 1.9.X. Does anyone have a good piece of code that pings that they would be willing to share.

Thanks

A: 

You can always do this and use regexps to parse the result or just check the exit status:

ping_count = 10
server = "www.google.com"
result = `ping -q -c #{ping_count} #{server}`
if ($?.exitstatus == 0) do
  puts "Device is up!"
end

Ping return values that you can check against:

The ping utility returns an exit status of zero if at least one response was heard from the specified host; a status of two if the transmission was successful but no responses were received; or another value (from <sysexits.h>) if an error occurred.

http://www.manpagez.com/man/8/ping

Mahmoud
Just checking to see if a device is up before I run the rest of my code. Also, tried your code, how do I see the results of the ping?
rahrahruby
See edited answer.
Mahmoud
+2  A: 

If by 'site' you mean website, then I wouldn't use ping. Ping will tell you if the host is up (unless a router or firewall is blocking ICMP), but it won't tell you if your web server or web app is responding properly.

If that's the case, I'd recommend Net::HTTP from the standard library, or any of the other HTTP libraries. One way to do it is:

def up?(site)
  Net::HTTP.new(site).head('/').kind_of? Net::HTTPOK
end

up? 'www.google.com' #=> true
Mark Thomas
Also site can deny non-browser requests. Compare www.habrahabr.ru and www.google.ru. So you need look into response more closely and/or play with user-agents.
Nakilon