Class: Rev::DNSResolver

Inherits:
IOWatcher show all
Defined in:
lib/rev/dns_resolver.rb

Direct Known Subclasses

TCPSocket::TCPConnectResolver

Defined Under Namespace

Classes: Timeout

Constant Summary collapse

RESOLV_CONF =
'/etc/resolv.conf'
HOSTS =
'/etc/hosts'
DNS_PORT =
53
DATAGRAM_SIZE =
512
TIMEOUT =

Retry timeout for each datagram sent

3
RETRIES =

Number of retries to attempt

4

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from IOWatcher

#disable, #enable, #on_writable

Methods inherited from Watcher

#attached?, #disable, #enable, event_callback, #evloop, watcher_delegate

Constructor Details

#initialize(hostname, *nameservers) ⇒ DNSResolver

Returns a new instance of DNSResolver.



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

def initialize(hostname, *nameservers)
  if nameservers.nil? or nameservers.empty?
    nameservers = File.read(RESOLV_CONF).scan(/^\s*nameserver\s+([0-9.:]+)/).flatten
    raise RuntimeError, "no nameservers found in #{RESOLV_CONF}" if nameservers.empty?
  end

  @nameservers = nameservers
  @request = request_message hostname
  @question = request_question hostname

  @socket = UDPSocket.new
  @timer = Timeout.new(self)
  super(@socket)
end

Class Method Details

.hosts(host) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/rev/dns_resolver.rb', line 28

def self.hosts(host)
  hosts = {}
  File.open(HOSTS).each_line do |host_entry|
    entries = host_entry.gsub(/#.*$/, '').gsub(/\s+/, ' ').split(' ')
    addr = entries.shift
    entries.each { |e| hosts[e] ||= addr }
  end

  hosts[host]
end

Instance Method Details

#attach(evloop) ⇒ Object



54
55
56
57
58
# File 'lib/rev/dns_resolver.rb', line 54

def attach(evloop)
  send_request
  @timer.attach(evloop)
  super
end

#detachObject



60
61
62
63
# File 'lib/rev/dns_resolver.rb', line 60

def detach
  @timer.detach if @timer.attached?
  super
end

#on_failureObject

Called when we receive a response indicating the name didn’t resolve



76
# File 'lib/rev/dns_resolver.rb', line 76

def on_failure; end

#on_success(address) ⇒ Object

Called when the name has successfully resolved to an address



72
# File 'lib/rev/dns_resolver.rb', line 72

def on_success(address); end

#on_timeoutObject

Called if we don’t receive a response



80
# File 'lib/rev/dns_resolver.rb', line 80

def on_timeout; end

#send_requestObject

Send a request to the DNS server



66
67
68
69
# File 'lib/rev/dns_resolver.rb', line 66

def send_request
  @socket.connect @nameservers.first, DNS_PORT
  @socket.send @request, 0
end