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 package dns
import ( import (
"bufio"
"fmt" "fmt"
"net/netip"
"os" "os"
"regexp" "strings"
) )
var ( const resolvConf = "/etc/resolv.conf"
// nameserver xxx.xxx.xxx.xxx
nameserverPattern = regexp.MustCompile(`nameserver\s+(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`)
)
func dnsReadConfig() (servers []string, err error) { func dnsReadConfig() (servers []string, err error) {
content, err := os.ReadFile("/etc/resolv.conf") file, err := os.Open(resolvConf)
if err != nil { 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 return
} }
for _, line := range nameserverPattern.FindAllStringSubmatch(string(content), -1) { defer func() { _ = file.Close() }()
addr := line[1] scanner := bufio.NewScanner(file)
servers = append(servers, addr) 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 return
} }