I want to check for a connection to a specific server with Ruby. So I just wrap the HTTP request into a begin/rescue construct and try again in a few seconds if the connection is not available.
Problem: If I start the program with no connection available (link down) it will never succeed in finding a connection even if at some time the connection is available (e.g. via ping, browser request).
Code:
require 'net/http'
loop do
begin
uri = URI.parse 'http://www.example.com'
resp = Net::HTTP.get uri
rescue SocketError => se
puts se
sleep 3
next
rescue Exception => e
puts e
break
end
puts 'It works!'
break
end
Steps to reproduce:
- Take network link down
- Start program
- -> getaddrinfo: Name or service not known
- -> ...
- Turn network link on again
- Still no connection, same error
Why is that?
Ruby version: ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux]