/
hostsfile.go
75 lines (63 loc) · 1.43 KB
/
hostsfile.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package hostsfile
import (
"errors"
"fmt"
"net"
"os"
"runtime"
"strings"
"github.com/projectdiscovery/fileutil"
"github.com/projectdiscovery/stringsutil"
)
const (
localhostName = "localhost"
)
func Path() string {
if isWindows() {
return fmt.Sprintf(`%s\System32\Drivers\etc\hosts`, os.Getenv("SystemRoot"))
}
return "/etc/hosts"
}
func ParseDefault() (map[string][]string, error) {
return Parse(Path())
}
func Parse(p string) (map[string][]string, error) {
if !fileutil.FileExists(p) {
return nil, errors.New("hosts file doesn't exist")
}
hostsFileCh, err := fileutil.ReadFile(p)
if err != nil {
return nil, err
}
items := make(map[string][]string)
for line := range hostsFileCh {
line = strings.TrimSpace(line)
// skip comments and empty lines
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// discard comment part
if strings.Contains(line, "#") {
line = stringsutil.Before(line, "#")
}
tokens := strings.Fields(line)
if len(tokens) > 1 {
ip := tokens[0]
for _, hostname := range tokens[1:] {
items[hostname] = append(items[hostname], ip)
}
}
}
// windows 11 resolves localhost with system dns resolver
if _, ok := items[localhostName]; !ok && isWindows() {
localhostIPs, err := net.LookupHost(localhostName)
if err != nil {
return nil, err
}
items[localhostName] = localhostIPs
}
return items, nil
}
func isWindows() bool {
return runtime.GOOS == "windows"
}