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

前端 未结 2 1618
孤城傲影
孤城傲影 2021-01-07 00:12

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 installe

2条回答
  •  死守一世寂寞
    2021-01-07 01:17

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

提交回复
热议问题