-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns_unix.go
71 lines (62 loc) · 1.59 KB
/
dns_unix.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
//go:build !windows
package dns
import (
"bufio"
"fmt"
"os"
"regexp"
"runtime"
"strings"
"github.com/wwqdrh/gokit/logger"
)
// listen address of systemd-resolved
const resolvedAddr = "127.0.0.53"
const resolvedConf = "/run/systemd/resolve/resolv.conf"
// GetLocalDomains get domain search postfixes
func GetLocalDomains() string {
f, err := os.Open(ResolvConf)
if err != nil {
return ""
}
defer f.Close()
var localDomains []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, FieldDomain) {
localDomains = append(localDomains, strings.TrimSpace(strings.TrimPrefix(line, FieldDomain)))
} else if strings.HasPrefix(line, FieldSearch) {
for _, s := range strings.Split(strings.TrimPrefix(line, FieldSearch), " ") {
if s != "" {
localDomains = append(localDomains, s)
}
}
}
}
return strings.Join(localDomains, ",")
}
// GetNameServer get primary dns server
func GetNameServer() string {
ns := fetchNameServerInConf(ResolvConf)
if runtime.GOOS == "linux" && ns == resolvedAddr {
logger.DefaultLogger.Debug("Using systemd-resolved")
return fetchNameServerInConf(resolvedConf)
}
return ns
}
func fetchNameServerInConf(resolvConf string) string {
f, err := os.Open(resolvConf)
if err != nil {
return ""
}
defer f.Close()
scanner := bufio.NewScanner(f)
pattern, _ := regexp.Compile(fmt.Sprintf("^%s[ \t]+"+IpAddrPattern, FieldNameserver))
for scanner.Scan() {
line := scanner.Text()
if pattern.MatchString(line) {
return strings.TrimSpace(strings.TrimPrefix(line, FieldNameserver))
}
}
return ""
}