0

コンソールから取得した IP 範囲のタイムアウトを処理したいのですが、取得した範囲内の 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 に答える