Shortening socket timeout using Timeout::timeout(n) does not seem to work for me
Asked Answered
B

2

2

I found what I thought should work perfectly at https://stackoverflow.com/questions/517219?tab=oldest#tab-top but, it did not work for me.

I have Ruby 1.9.1 installed on Windows and, when I try the example "is_port_open" test, it does not work. The socket call still takes around 20 seconds to timeout no matter what value I set for the timeout. Any ideas why?

Beautician answered 12/8, 2010 at 3:29 Comment(0)
D
5

The following code seems to work with ruby 1.9.1 on Windows:

require 'socket'

def is_port_open?(ip, port)
  s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
  sa = Socket.sockaddr_in(port, ip)

  begin
    s.connect_nonblock(sa)
  rescue Errno::EINPROGRESS
    if IO.select(nil, [s], nil, 1)
      begin
        s.connect_nonblock(sa)
      rescue Errno::EISCONN
        return true
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        return false
      end
    end
  end

  return false
end

I haven't figured out yet why the original is_port_open?() code doesn't work on Windows with ruby 1.9.1 (it works on other OSes).

Derrik answered 13/8, 2010 at 1:12 Comment(0)
S
0

This may be due to some inherent problems with Rubys Timeout library. You can achieve this by directly accessing the underlying socket library and setting timeouts on the Socket. This article covers this in some depth, although it assumes *nix so you may have some issues with Windows, I'm not sure how similar the socket implementations are.

Sulphide answered 12/8, 2010 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.