# frozen_string_literal: true require "resolv" class Netdisco class Resolve # 对象实例化入口函数 def initialize @cache_ip = {} @cache_name = {} end # @param [String] name DNS name which we try to resolve to IP # @return [String, nil] string if name resolves to IP, otherwise nil # 优先加载缓存,不能存在则实时采集 def getip(name) if @cache_ip.has_key? name @cache_ip[name] else # 可能一个 name 同时存在 IPV4 和 IPV6 解析 begin if CFG.dns.afi == "ipv4" @cache_ip[name] = Resolv::DNS.new.getresource(name, Resolv::DNS::Resource::IN::A).address elsif CFG.dns.afi == "ipv6" @cache_ip[name] = Resolv::DNS.new.getresource(name, Resolv::DNS::Resource::IN::AAAA).address else @cache_ip[name] = Resolv.getaddress name end rescue StandardError => e Log.debug "DNS resolution/getip for '#{name}' raised error '#{e.class}' with message '#{e.message}'" nil end end end # @param [String] ip DNS IP which we try to resolve to name # @return [String] name if it resolves, ip otherwise # 优先加载缓存,不能存在则实时采集 def getname(ip) if @cache_name.has_key? ip @cache_name[ip] else begin @cache_name[ip] = Resolv.getname ip rescue StandardError => e Log.debug "DNS resolution/getname for '#{ip}' raised error '#{e.class}' with message '#{e.message}'" @cache_name[ip] = ip ip end end end end DNS = Resolve.new end