Hello,

On 15 ŽÁŽ┼Ž┬ 2014, at 02:36 , cynic limbu <lists / ruby-forum.com> wrote:

> Cory Cory wrote in post #647411:
>> Does anyone know a way to test to see if the computer is connected to
>> the internet in Ruby?
> 
> Apologies for necro threading but let my answer help other people coming 
> to this link via google.
> 
> if system("ping google.com")
> puts "Connected to the internet."
> else puts "No internet connection."
> end
> 

The code is not completely wrong but in real case scenarios is impractical.

First off you need to issue a command that will send 1 ping request (or at least a finite number), otherwise
the process will never end. So you should use something like 'ping -c 1 some.host'.

Second, you need to somehow handle kernel#system output which is not *easy*. Either you have to redirect the output to /dev/null in which scenario
you might better of using bash instead of ruby all together, or use a gem to handle everything for you and return just true/false:
--
#!/usr/bin/env ruby

require 'net/ping'

def up?(host)
    check  = Net::Ping::TCP.new(host)
    check.ping
end

chost  = '10.0.0.1'
puts up?(chost) # returns true if ping replies
--

Generally speaking though, it's better to use other approaches like backticks or open3[1] which are considered more 'secure' and offer more options, although kinda hard to grasp at first.

[1] http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open3/rdoc/Open3.html

> -- 
> Posted via http://www.ruby-forum.com/.


Panagiotis (atmosx) Atmatzidis

email:	atma / convalesco.org
URL:	http://www.convalesco.org
GnuPG ID: 0x1A7BFEC5
gpg --keyserver pgp.mit.edu --recv-keys 1A7BFEC5
--
The wise man said: "Never argue with an idiot. They bring you down to their level and beat you with experience."