0

我想处理从控制台获取的 IP 范围的超时,我为此向获取范围内的 IP 发出请求并出现超时错误。我想向所有 IP 发出请求并得到它们的响应。对于超时的IP,想跳过它并移动到下一个。如何处理这个问题,这样循环就不会出现异常,并且脚本会向所有可以提供响应处理超时的 IP 发送请求。

在此附上代码:

require 'net/http'
require 'uri'
require 'ipaddr'

puts "Origin IP:"
originip = gets()
(IPAddr.new("209.85.175.121")..IPAddr.new("209.85.175.150")).each do |address|
  req = Net::HTTP.get(URI.parse("http://#{address.to_s}"))
  puts req
end

错误:

C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `initialize': A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. - connect(2) (Errno::ETIMEDOUT)
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `open'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `connect'
        from C:/Ruby187/lib/ruby/1.8/timeout.rb:53:in `timeout'
        from C:/Ruby187/lib/ruby/1.8/timeout.rb:101:in `timeout'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `connect'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:553:in `do_start'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:542:in `start'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:379:in `get_response'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:356:in `get'
        from IP Range 2.rb:9
        from IP Range 2.rb:8:in `each'
4

2 回答 2

1

就像马克说的那样。您应该挽救异常。像这样:

begin
  response = Net::HTTP.get(...)
rescue Errno::ECONNREFUSED => e
  # Do what you think needs to be done
end

此外,您从调用中得到的get()是响应,而不是请求。

于 2012-02-20T19:45:04.827 回答
0

使用timeout捕获异常,

require 'timeout'

(IPAddr.new("209.85.175.121")..IPAddr.new("209.85.175.150")).each do |address|
  begin
    req = Net::HTTP.get(URI.parse("http://#{address.to_s}"))
    puts req
  rescue Timeout::Error => exc
    puts "ERROR: #{exc.message}"
  rescue Errno::ETIMEDOUT => exc
    puts "ERROR: #{exc.message}"
  # uncomment the following two lines, if you are not able to track the exception type.
  #rescue Exception => exc
  #  puts "ERROR: #{exc.message}"
  end
end

编辑:当我们救援时,只会捕获Timeout::Error属于类的那些异常。Timeout::Error我们需要使用它们的错误类来捕获引发的异常,并相应地更新代码。

于 2012-02-20T16:20:30.730 回答