Skip to content

Instantly share code, notes, and snippets.

@DiogoAndre
Last active January 3, 2024 09:08
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save DiogoAndre/5056521 to your computer and use it in GitHub Desktop.
Save DiogoAndre/5056521 to your computer and use it in GitHub Desktop.
Simple ICMP Ping script in Ruby. Using the Net-Ping gem https://github.com/djberg96/net-ping
require 'net/ping'
@icmp = Net::Ping::ICMP.new('142.40.81.34')
rtary = []
pingfails = 0
repeat = 5
puts 'starting to ping'
(1..repeat).each do
if @icmp.ping
rtary << @icmp.duration
puts "host replied in #{@icmp.duration}"
else
pingfails += 1
puts "timeout"
end
end
avg = rtary.inject(0) {|sum, i| sum + i}/(repeat - pingfails)
puts "Average round-trip is #{avg}\n"
puts "#{pingfails} packets were droped"
run ping.rb
@johngrindal
Copy link

the duration function is not working for me, any ideas why

@john916
Copy link

john916 commented Oct 1, 2015

I was trying to rewrite this program so that it asks for the IP address to ping but have not had any luck. Can you help me out? I am new to programming and Ruby is the first language I'm studying. Thanks!

@john916
Copy link

john916 commented Oct 5, 2015

I changed line 3 to: @icmp = Net::Ping::ICMP.new(ARGV[0]) and now I can type, "ruby ping.rb 8.8.8.8" and it will ping 8.8.8.8 or whatever URL or IP address you type in. I wanted to actually use get.chomp with an "Enter the IP address or URL" dialog, but this works for now.

@newlandk
Copy link

I took some inspiration from this and made some adjustments for my own purposes. Hopefully it's helpful.

https://gist.github.com/newlandk/20521c9abf85a4db9a32

@john916, you're probably looking for
print "Hostname: "
host = STDIN.gets.chomp

@illtellyoulater
Copy link

illtellyoulater commented Oct 23, 2017

Having same issue @johngrindal described: the duration function not working. Does anyone know why? I'm on Windows.

@illtellyoulater
Copy link

illtellyoulater commented Oct 23, 2017

Ok I figured it out: I was calling @my_ping.duration before actually executing the ping with @my_ping.ping 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment