Ruby'套接字'超时问题

时间:2014-01-25 07:01:29

标签: ruby

我有以下连接到HTTP主机的功能。我想正确使用超时。有时似乎有效,但有时却没有,只是永远挂起:

def http_send(host, packet, port, timeout = 6)
  addr = Socket.getaddrinfo(host, nil)
  sockaddr = Socket.pack_sockaddr_in(port, addr[0][3])

  Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0).tap do |socket|
    socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)

    begin
      socket.connect_nonblock(sockaddr)
    rescue IO::WaitWritable
      if IO.select(nil, [socket], nil, timeout)
        begin
          socket.connect_nonblock(sockaddr)
          socket.write(packet)
          return socket.read
        rescue Errno::EISCONN
        rescue
          socket.close
          puts "[!] Unexpected exception!"
        end
      else
        socket.close
        puts "[!] Connection timeout!"
      end
    end
  end
end

知道为什么会这样吗?谢谢!

1 个答案:

答案 0 :(得分:-1)

这对我有用:

    require 'ipscanner'
require 'socket'
require 'thread'

def open_port(host, port)
  sock = Socket.new(:INET, :STREAM)
  raw = Socket.sockaddr_in(port, host)
  #sock.setsockopt( :INET, :connect_timeout, 1 )
  puts "#{host}: #{port} open." if sock.connect(raw)

rescue(Errno::ECONNREFUSED)
rescue(Errno::ETIMEDOUT)
end

def main(host, ports)
threads = []

        ports.each do |makethread|
                threads[makethread] = Thread.new do
                open_port(host, makethread)
                end
        end
end


start_port=1
end_port=700
ip_range_1=200
ip_range_2=200

allports=*(start_port..end_port)
pc=IPScanner.scan(ip_base = '10.166.10.', range = ip_range_1..ip_range_2, t = 5)

pc.each do |pc_ip|
main pc_ip, allports
end