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

时光怂恿深爱的人放手 提交于 2019-12-01 00:35:35

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!