Class: Celluloid::IO::DNSResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/celluloid/io/dns_resolver.rb

Overview

Asynchronous DNS resolver using Celluloid::IO::UDPSocket

Constant Summary collapse

MAX_PACKET_SIZE =

Maximum UDP packet we'll accept

512
DNS_PORT =
53

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDNSResolver


23
24
25
26
27
28
29
30
31
32
33
# File 'lib/celluloid/io/dns_resolver.rb', line 23

def initialize
  # early return for edge case when there are no nameservers configured
  # but we still want to be able to static lookups using #resolve_hostname
  @nameservers = self.class.nameservers or return

  @server = IPAddr.new(@nameservers.sample)

  # The non-blocking secret sauce is here, as this is actually a
  # Celluloid::IO::UDPSocket
  @socket = UDPSocket.new(@server.family)
end

Class Method Details

.generate_idObject


15
16
17
# File 'lib/celluloid/io/dns_resolver.rb', line 15

def self.generate_id
  @mutex.synchronize { @identifier = (@identifier + 1) & 0xFFFF }
end

.nameserversObject


19
20
21
# File 'lib/celluloid/io/dns_resolver.rb', line 19

def self.nameservers
  Resolv::DNS::Config.default_config_hash[:nameserver]
end

Instance Method Details

#resolve(hostname) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/celluloid/io/dns_resolver.rb', line 35

def resolve(hostname)
  if host = resolve_hostname(hostname)
    unless ip_address = resolve_host(host)
      raise Resolv::ResolvError, "invalid entry in hosts file: #{host}"
    end
    return ip_address
  end

  query = build_query(hostname)
  @socket.send query.encode, 0, @server.to_s, DNS_PORT
  data, _ = @socket.recvfrom(MAX_PACKET_SIZE)
  response = Resolv::DNS::Message.decode(data)

  addrs = []
  # The answer might include IN::CNAME entries so filters them out
  # to include IN::A & IN::AAAA entries only.
  response.each_answer { |name, ttl, value| addrs << value.address if value.respond_to?(:address) }

  return if addrs.empty?
  return addrs.first if addrs.size == 1
  addrs
end