为 Ruby Resolv.getaddress(ip) 设置超时

Set a timeout for Ruby Resolv.getaddress(ip)

我找不到 in the Ruby documentation 任何关于如何设置超时以使用 Resolv class 中的 class 方法 getaddress 检索域 IP 的任何信息——来自 Ruby标准库。

查看 Resolv 的 source code,在第 353 行,我可以看到在 DNS class 中定义了一个名为 timeouts 的方法。您应该可以使用它来更改超时。

    # Sets the resolver timeouts.  This may be a single positive number
    # or an array of positive numbers representing timeouts in seconds.
    # If an array is specified, a DNS request will retry and wait for
    # each successive interval in the array until a successful response
    # is received.  Specifying +nil+ reverts to the default timeouts:
    # [ 5, second = 5 * 2 / nameserver_count, 2 * second, 4 * second ]
    #
    # Example:
    #
    #   dns.timeouts = 3
    #
    def timeouts=(values)
      @config.timeouts = values
    end

超时选项可以这样使用:

Resolv::DNS.open do |dns|
  dns.timeouts = 1
  host = dns.getname "172.28.0.1"
  puts "hostname: #{host}"
end