Can't use a timeout with Socket::getaddrinfo

R

Ruby Nuby

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.
 
J

Joel VanderWerf

Ruby said:
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.

Try resolv.rb in the standard library?
 
R

Ruby Nuby

Joel said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top