Class: Netdisco::Resolve

Inherits:
Object
  • Object
show all
Defined in:
lib/netdisco/dns.rb

Instance Method Summary collapse

Constructor Details

#initializeResolve

对象实例化入口函数



8
9
10
11
# File 'lib/netdisco/dns.rb', line 8

def initialize
  @cache_ip   = {}
  @cache_name = {}
end

Instance Method Details

#getip(name) ⇒ String?

优先加载缓存,不能存在则实时采集

Parameters:

  • name (String)

    DNS name which we try to resolve to IP

Returns:

  • (String, nil)

    string if name resolves to IP, otherwise nil



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/netdisco/dns.rb', line 16

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

#getname(ip) ⇒ String

优先加载缓存,不能存在则实时采集

Parameters:

  • ip (String)

    DNS IP which we try to resolve to name

Returns:

  • (String)

    name if it resolves, ip otherwise



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/netdisco/dns.rb', line 39

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