Can't use a timeout with Socket::getaddrinfo

Does anyone know how to successfully implement a timeout with
Socket::getaddrinfo? This function works great against IP addresses
that are resolvable. In other cases where DNS can’t find a hostname,
getaddrinfo can act as a bottle neck. In my script, all I’d really like
to do is set a timeout to about 1 or 2 seconds, then simply move on if
the IP cannot be resolved. So I’ve tried something like this:

timeout(2) {

begin
puts “#{Socket::getaddrinfo(ARGV[0], “echo”,
Socket::AF_INET,Socket::SOCK_DGRAM)[0][2]}”
rescue(Timeout::Error)
puts “rescue has been reached”
puts ARGV[0]
end
}

In this case, you’d expect that if DNS can’t find the IP, it would time
out in 2 seconds and reach the rescue. Instead, it takes like 10 or 15
seconds, then reaches the rescue. I’d like to know why the rescue code
is being reached if the timeout of 2 seconds isn’t being used. Also, is
there a way for me to correctly implement a timeout on
Socket:getaddrinfo?

Thanks in advance, fellow Rubyists.

Ruby N. wrote:

begin
seconds, then reaches the rescue. I’d like to know why the rescue code
is being reached if the timeout of 2 seconds isn’t being used. Also, is
there a way for me to correctly implement a timeout on
Socket:getaddrinfo?

Thanks in advance, fellow Rubyists.

Try resolv.rb in the standard library?

Joel VanderWerf wrote:

Ruby N. wrote:

begin
seconds, then reaches the rescue. I’d like to know why the rescue code
is being reached if the timeout of 2 seconds isn’t being used. Also, is
there a way for me to correctly implement a timeout on
Socket:getaddrinfo?

Thanks in advance, fellow Rubyists.

Try resolv.rb in the standard library?

Awesome. Resolv.getname(ip)… Thanks. I didn’t realize it was going
to be that easy. I assumed there were lower level socket options that
needed to be set. Resolv.getname works well with timeouts.

I appreciate the feedback.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs