Class: Resolv::Hosts

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

Overview

Resolves names and addresses using the hosts file, “/etc/hosts” or whatever it is on Windows.

Constant Summary collapse

DefaultFileName =
'/etc/hosts'

Instance Method Summary collapse

Constructor Details

#initialize(filename = DefaultFileName) ⇒ Hosts

Returns a new instance of Hosts.



335
336
337
338
339
# File 'lib/net/dns/resolv.rb', line 335

def initialize(filename = DefaultFileName)
  @filename = filename
  @mutex = Mutex.new
  @initialized = nil
end

Instance Method Details

#each_address(name, &proc) ⇒ Object



383
384
385
386
387
388
# File 'lib/net/dns/resolv.rb', line 383

def each_address(name, &proc)
  lazy_initialize
  if @name2addr.include?(name)
    @name2addr[name].each(&proc)
  end
end

#each_name(address, &proc) ⇒ Object



401
402
403
404
405
406
# File 'lib/net/dns/resolv.rb', line 401

def each_name(address, &proc)
  lazy_initialize
  if @addr2name.include?(address)
    @addr2name[address].each(&proc)
  end
end

#getaddress(name) ⇒ Object

Raises:



372
373
374
375
# File 'lib/net/dns/resolv.rb', line 372

def getaddress(name)
  each_address(name) {|address| return address}
  raise ResolvError.new("#{@filename} has no name: #{name}")
end

#getaddresses(name) ⇒ Object



377
378
379
380
381
# File 'lib/net/dns/resolv.rb', line 377

def getaddresses(name)
  ret = []
  each_address(name) {|address| ret << address}
  return ret
end

#getname(address) ⇒ Object

Raises:



390
391
392
393
# File 'lib/net/dns/resolv.rb', line 390

def getname(address)
  each_name(address) {|name| return name}
  raise ResolvError.new("#{@filename} has no address: #{address}")
end

#getnames(address) ⇒ Object



395
396
397
398
399
# File 'lib/net/dns/resolv.rb', line 395

def getnames(address)
  ret = []
  each_name(address) {|name| ret << name}
  return ret
end

#lazy_initializeObject

:nodoc:



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/net/dns/resolv.rb', line 341

def lazy_initialize # :nodoc:
  @mutex.synchronize {
    unless @initialized
      @name2addr = {}
      @addr2name = {}
      open(@filename) {|f|
        f.each {|line|
          line.sub!(/#.*/, '')
          addr, hostname, *aliases = line.split(/\s+/)
          next unless addr
          addr.untaint
          hostname.untaint
          @addr2name[addr] = [] unless @addr2name.include? addr
          @addr2name[addr] << hostname
          @addr2name[addr] += aliases
          @name2addr[hostname] = [] unless @name2addr.include? hostname
          @name2addr[hostname] << addr
          aliases.each {|n|
            n.untaint
            @name2addr[n] = [] unless @name2addr.include? n
            @name2addr[n] << addr
          }
        }
      }
      @name2addr.each {|name, arr| arr.reverse!}
      @initialized = true
    end
  }
  self
end