Class: Async::DNS::System::Hosts

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

Overview

An interface for querying the system’s hosts file.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHosts

Create a new hosts file interface.



60
61
62
63
# File 'lib/async/dns/system.rb', line 60

def initialize
	@addresses = {}
	@names = {}
end

Class Method Details

.localObject

Hosts for the local system.



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/async/dns/system.rb', line 45

def self.local
	hosts = self.new
	
	path = System.hosts_path
	
	if path and File.exist?(path)
		File.open(path) do |file|
			hosts.parse_hosts(file)
		end
	end
	
	return hosts
end

Instance Method Details

#add(address, names) ⇒ Object

Add a new address with the given names.



81
82
83
84
85
86
87
88
89
90
91
# File 'lib/async/dns/system.rb', line 81

def add(address, names)
	@addresses[address] ||= []
	@addresses[address] += names
	
	names.each do |name|
		name = Resolv::DNS::Name.create(name).with_origin(nil)
		
		@names[name] ||= []
		@names[name] << address
	end
end

#each(&block) ⇒ Object



93
94
95
# File 'lib/async/dns/system.rb', line 93

def each(&block)
	@names.each(&block)
end

#lookup(name, origin: nil) ⇒ Object Also known as: []

Lookup a name in the hosts file.



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/async/dns/system.rb', line 66

def lookup(name, origin: nil)
	name = Resolv::DNS::Name.create(name).with_origin(origin)
	
	addresses = @names[name]
	
	if addresses
		addresses.last
	else
		nil
	end
end

#parse_hosts(io) ⇒ Object

Parse a hosts file and add the entries.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/async/dns/system.rb', line 98

def parse_hosts(io)
	io.each do |line|
		line.sub!(/#.*/, "")
		address, hostname, *aliases = line.split(/\s+/)
		
		if address =~ Resolv::IPv4::Regex
			address = Resolv::IPv4.create(address)
		elsif address =~ Resolv::IPv6::Regex
			address = Resolv::IPv6.create(address)
		else
			next
		end
		
		add(address, [hostname] + aliases)
	end
end