Async::DNS SourceAsyncDNSSystemHosts

class Hosts

An interface for querying the system's hosts file.

Definitions

def self.local

Hosts for the local system.

Implementation

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

def initialize

Create a new hosts file interface.

Implementation

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

def call(name)

This is used to match names against the list of known hosts:

Implementation

def call(name)
	@names.include?(name)
end

def lookup(name)

Lookup a name in the hosts file.

Implementation

def lookup(name)
	addresses = @names[name]
	
	if addresses
		addresses.last
	else
		nil
	end
end

def add(address, names)

Add a new address with the given names.

Implementation

def add(address, names)
	@addresses[address] ||= []
	@addresses[address] += names
	
	names.each do |name|
		@names[name] ||= []
		@names[name] << address
	end
end

def parse_hosts(io)

Parse a hosts file and add the entries.

Implementation

def parse_hosts(io)
	io.each do |line|
		line.sub!(/#.*/, '')
		address, hostname, *aliases = line.split(/\s+/)
		
		add(address, [hostname] + aliases)
	end
end