使用net / http跳过无响应的主机

时间:2016-06-28 21:29:22

标签: ruby

我正在使用net / http向一些内部IP地址发送一堆请求。

以下是代码片段:

  File.open("internalcorpIPs", "r") do |f|
    f.each_line do |line|
      puts line
      res = Net::HTTP.get_response(URI.parse(line))
      getCode = res.code
    end
  end

我只是向http://IPhttps://IP发出请求,但似乎此方法仅在每个IP /线路地址都有效时才有效。如何跳过没有网络服务器(或80/443端口)的IP地址?

是否可以让它读取该行,如果没有返回响应代码,则转到下一行?

谢谢!

1 个答案:

答案 0 :(得分:2)

你可以简单地将你的请求包装在DATEDIFF块中,如下所示:

begin/rescue

但是你会在超时之前至少等待60秒,所以我建议减少超时。此外,您可以引入一个额外的保护子句来检查uri是否包含方案 File.open("internalcorpIPs", "r") do |f| f.each_line do |line| puts line begin # strip and encode uri from the file uri = URI.parse(URI.encode(line.strip)) res = Net::HTTP.get_response(uri) getCode = res.code rescue Timeout::Error => e puts e false end end end http://,否则引发异常(或其他)。

https://

附加说明:

打开超时

  

等待连接打开的秒数。可以使用任何数字,包括小数秒的浮点数。如果HTTP对象在这么多秒内无法打开连接,则会引发Net :: OpenTimeout异常。默认值为60秒。

读取超时

  

等待读取一个块的秒数(通过一次读取(2)调用)。可以使用任何数字,包括小数秒的浮点数。如果HTTP对象在这么多秒内无法读取数据,则会引发Net :: ReadTimeout异常。默认值为60秒。

URI计划

通用uri(require 'net/http' File.open("internalcorpIPs", "r") do |f| f.each do |line| puts line begin # strip and encode uri from the file uri = URI.parse(URI.encode(line.strip)) # if uri misses the schema (http:// or https://) -> raise error raise URI::Error, "uri #{uri} miss the scheme" unless uri.scheme http = Net::HTTP.new(uri.host, uri.port) http.open_timeout = 2 # seconds http.read_timeout = 2 # seconds http.start do |conn| response = conn.request_get(path = '/') puts response.code end rescue Timeout::Error, URI::Error, SocketError => e puts e false end end end )和http uri(URI::Generic)之间的区别。

URI::HTTP

参考:

希望它有所帮助!

更新

URI.parse接受字符串作为参数,并在未指定时自动设置端口:

 uri = URI.parse('1.1.1.1')
 => #<URI::Generic 1.1.1.1> 
 uri.scheme
 => nil 
 uri.host
 => nil 
 uri.port
 => nil 
 uri.path
 => "1.1.1.1" 

 uri = URI.parse('http://1.1.1.1')
 => #<URI::HTTP http://1.1.1.1> 
 uri.scheme
 => "http" 
 uri.host
 => "1.1.1.1" 
 uri.port
 => 80 
 uri.path
 => ""