Programming: Beginners Ruby: How to inquire about your network speed
From the icmp-echo-average dept. (4451) (0) by Luis
So you are totally new to programming on a computer and you want to see how programs are done. The usual recommendation is "find a problem that you like and attempt to solve it using a programming language of your choice". In other words, if you already have the hang on how to write computer programs and you want to learn a new language, say Ruby, then you just need to try to solve known problems.
Here is a simple problem and its solution written in very simple Ruby. We will be writing a program that tests the speed of our network connection to the Google DNS 188.8.131.52. You will need Ruby 1.9 to get this to work properly, as well as the net-ping gem. On an Ubuntu (11.10) system you can get these by doing:
sudo apt-get install ruby19
And then you can use "gem" to install net-ping like:
sudo gem install net-ping
Once you have those components installed, you can proceed to your program. Using a text editor (Activities->Accessories->Text Editor) create a new file and call it ping.rb. Then copy/paste this code:
begin require 'net/ping' times =  1.upto(1000) do obj = Net::Ping::ICMP.new("184.108.40.206") obj.ping times << obj.duration end avg = times.reduce(:+) / times.size puts avg rescue => e error e.message end
You can edit the properties of the file and make sure it is executable. Then from a Terminal you can execute:
$> sudo ./ping.rb 0.0006391874500000002
And this shows you the average time it takes to do 1000 inquiries to the host with IP 220.127.116.11 (Google DNS) is 0.6 milli seconds (ms), which is extremely fast!
(full disclosure: this was not the original IP used to get that result, in reality I ping my own local router IP. There is no way I could get 0.6 to Google DNS over the public Internet :D)