How to ping for reachability of remote host in Ruby
If you're on a *nix machine (OSX/Linux/BSD...), you can always tell Ruby (by using back ticks) to use the command line and save the results.
x = `ping -c 1 10.102.52.42`
# do whatever with X
The -c 1
parameter tells it to run once. You can set this to any number you find fit. If you don't set -c
, it'll run until it's interrupted which will cause your program to stall.
Ping with External, UDP, HTTP, etc. Modify as you see fit. You can read more at ping-net git-repo.
1.
########################################################################
# example_pingexternal.rb
#
# A short sample program demonstrating an external ping. You can run
# this program via the example:external task. Modify as you see fit.
########################################################################
require 'net/ping'
good = 'www.rubyforge.org'
bad = 'foo.bar.baz'
p1 = Net::Ping::External.new(good)
p p1.ping?
p2 = Net::Ping::External.new(bad)
p p2.ping?
2.
########################################################################
# example_pinghttp.rb
#
# A short sample program demonstrating an http ping. You can run
# this program via the example:http task. Modify as you see fit.
########################################################################
require 'net/ping'
good = 'http://www.google.com/index.html'
bad = 'http://www.ruby-lang.org/index.html'
puts "== Good ping, no redirect"
p1 = Net::Ping::HTTP.new(good)
p p1.ping?
puts "== Bad ping"
p2 = Net::Ping::HTTP.new(bad)
p p2.ping?
p p2.warning
p p2.exception
3.
########################################################################
# example_pingtcp.rb
#
# A short sample program demonstrating a tcp ping. You can run
# this program via the example:tcp task. Modify as you see fit.
########################################################################
require 'net/ping'
good = 'www.google.com'
bad = 'foo.bar.baz'
p1 = Net::Ping::TCP.new(good, 'http')
p p1.ping?
p2 = Net::Ping::TCP.new(bad)
p p2.ping?
4.
ping-1.7.8/examples/example_pingudp.rb
########################################################################
# example_pingudp.rb
#
# A short sample program demonstrating a UDP ping. You can run
# this program via the example:udp task. Modify as you see fit.
########################################################################
require 'net/ping'
host = 'www.google.com'
u = Net::Ping::UDP.new(host)
p u.ping?
I use the net-ping
gem which you need to install. Then the code is easy:
#!/usr/bin/env ruby
require 'net/ping'
def up?(host)
check = Net::Ping::External.new(host)
check.ping?
end
chost = '10.0.0.1'
puts up?(chost) # prints "true" if ping replies