Sha256: 2ab9afa09001cfca7560feff41b24c8dbee79427717f949559f92154f7cb25cb

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

# 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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
netdisco-0.0.8 lib/netdisco/dns.rb