Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / net / hosts.go
blob556d57f112ddb90b5e5d802e19bd68f680939bc6
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.
7 package net
9 import (
10 "os"
11 "sync"
14 const cacheMaxAge = int64(300) // 5 minutes.
16 // hostsPath points to the file with static IP/address entries.
17 var hostsPath = "/etc/hosts"
19 // Simple cache.
20 var hosts struct {
21 sync.Mutex
22 data map[string][]string
23 time int64
24 path string
27 func readHosts() {
28 now, _, _ := os.Time()
29 hp := hostsPath
30 if len(hosts.data) == 0 || hosts.time+cacheMaxAge <= now || hosts.path != hp {
31 hs := make(map[string][]string)
32 var file *file
33 if file, _ = open(hp); file == nil {
34 return
36 for line, ok := file.readLine(); ok; line, ok = file.readLine() {
37 if i := byteIndex(line, '#'); i >= 0 {
38 // Discard comments.
39 line = line[0:i]
41 f := getFields(line)
42 if len(f) < 2 || ParseIP(f[0]) == nil {
43 continue
45 for i := 1; i < len(f); i++ {
46 h := f[i]
47 hs[h] = append(hs[h], f[0])
50 // Update the data cache.
51 hosts.time, _, _ = os.Time()
52 hosts.path = hp
53 hosts.data = hs
54 file.close()
58 // lookupStaticHosts looks up the addresses for the given host from /etc/hosts.
59 func lookupStaticHost(host string) []string {
60 hosts.Lock()
61 defer hosts.Unlock()
62 readHosts()
63 if len(hosts.data) != 0 {
64 if ips, ok := hosts.data[host]; ok {
65 return ips
68 return nil