chore: better resolv.conf parsing

This commit is contained in:
wwqgtxx 2023-06-28 09:17:40 +08:00
parent 603d0809b4
commit db6b2b7702

View file

@ -3,25 +3,41 @@
package dns
import (
"bufio"
"fmt"
"net/netip"
"os"
"regexp"
"strings"
)
var (
// nameserver xxx.xxx.xxx.xxx
nameserverPattern = regexp.MustCompile(`nameserver\s+(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`)
)
const resolvConf = "/etc/resolv.conf"
func dnsReadConfig() (servers []string, err error) {
content, err := os.ReadFile("/etc/resolv.conf")
file, err := os.Open(resolvConf)
if err != nil {
err = fmt.Errorf("failed to read /etc/resolv.conf: %w", err)
err = fmt.Errorf("failed to read %s: %w", resolvConf, err)
return
}
for _, line := range nameserverPattern.FindAllStringSubmatch(string(content), -1) {
addr := line[1]
servers = append(servers, addr)
defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if len(line) > 0 && (line[0] == ';' || line[0] == '#') {
// comment.
continue
}
f := strings.Fields(line)
if len(f) < 1 {
continue
}
switch f[0] {
case "nameserver": // add one name server
if len(f) > 1 {
if addr, err := netip.ParseAddr(f[1]); err == nil {
servers = append(servers, addr.String())
}
}
}
}
return
}