-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathhosts.go
54 lines (48 loc) · 1.28 KB
/
hosts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package hostsfile
import (
"io/ioutil"
"strings"
)
// ReadHostsFile reads the hosts file.
func ReadHostsFile() ([]byte, error) {
bs, err := ioutil.ReadFile(HostsPath)
if err != nil {
return nil, err
}
return bs, nil
}
// ParseHosts takes in hosts file content and returns a map of parsed results.
func ParseHosts(hostsFileContent []byte, err error) (map[string][]string, error) {
if err != nil {
return nil, err
}
hostsMap := map[string][]string{}
LINE:
for _, line := range strings.Split(strings.Trim(string(hostsFileContent), " \t\r\n"), "\n") {
line = strings.Replace(strings.Trim(line, " \t"), "\t", " ", -1)
if len(line) == 0 || line[0] == ';' || line[0] == '#' {
continue
}
pieces := strings.SplitN(line, " ", 2)
if len(pieces) > 1 && len(pieces[0]) > 0 {
if names := strings.Fields(pieces[1]); len(names) > 0 {
for _, name := range names {
if strings.HasPrefix(name, "#") {
continue LINE
}
hostsMap[pieces[0]] = append(hostsMap[pieces[0]], name)
}
}
}
}
return hostsMap, nil
}
// ReverseLookup takes an IP address and returns a slice of matching hosts file
// entries.
func ReverseLookup(ip string) ([]string, error) {
hostsMap, err := ParseHosts(ReadHostsFile())
if err != nil {
return nil, err
}
return hostsMap[ip], nil
}