1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Read static host/IP entries from /etc/hosts.
14 const cacheMaxAge
= 5 * time
.Minute
16 // hostsPath points to the file with static IP/address entries.
17 var hostsPath
= "/etc/hosts"
22 byName
map[string][]string
23 byAddr
map[string][]string
31 if len(hosts
.byName
) == 0 || now
.After(hosts
.expire
) || hosts
.path
!= hp
{
32 hs
:= make(map[string][]string)
33 is
:= make(map[string][]string)
35 if file
, _
= open(hp
); file
== nil {
38 for line
, ok
:= file
.readLine(); ok
; line
, ok
= file
.readLine() {
39 if i
:= byteIndex(line
, '#'); i
>= 0 {
44 if len(f
) < 2 ||
ParseIP(f
[0]) == nil {
47 for i
:= 1; i
< len(f
); i
++ {
49 hs
[h
] = append(hs
[h
], f
[0])
50 is
[f
[0]] = append(is
[f
[0]], h
)
53 // Update the data cache.
54 hosts
.expire
= time
.Now().Add(cacheMaxAge
)
62 // lookupStaticHost looks up the addresses for the given host from /etc/hosts.
63 func lookupStaticHost(host
string) []string {
67 if len(hosts
.byName
) != 0 {
68 if ips
, ok
:= hosts
.byName
[host
]; ok
{
75 // lookupStaticAddr looks up the hosts for the given address from /etc/hosts.
76 func lookupStaticAddr(addr
string) []string {
80 if len(hosts
.byAddr
) != 0 {
81 if hosts
, ok
:= hosts
.byAddr
[addr
]; ok
{