github.com/metacubex/mihomo@v1.18.5/dns/system_posix.go (about)

     1  //go:build !windows
     2  
     3  package dns
     4  
     5  import (
     6  	"bufio"
     7  	"fmt"
     8  	"net/netip"
     9  	"os"
    10  	"strings"
    11  )
    12  
    13  const resolvConf = "/etc/resolv.conf"
    14  
    15  func dnsReadConfig() (servers []string, err error) {
    16  	file, err := os.Open(resolvConf)
    17  	if err != nil {
    18  		err = fmt.Errorf("failed to read %s: %w", resolvConf, err)
    19  		return
    20  	}
    21  	defer func() { _ = file.Close() }()
    22  	scanner := bufio.NewScanner(file)
    23  	for scanner.Scan() {
    24  		line := scanner.Text()
    25  		if len(line) > 0 && (line[0] == ';' || line[0] == '#') {
    26  			// comment.
    27  			continue
    28  		}
    29  		f := strings.Fields(line)
    30  		if len(f) < 1 {
    31  			continue
    32  		}
    33  		switch f[0] {
    34  		case "nameserver": // add one name server
    35  			if len(f) > 1 {
    36  				if addr, err := netip.ParseAddr(f[1]); err == nil {
    37  					servers = append(servers, addr.String())
    38  				}
    39  			}
    40  		}
    41  	}
    42  	return
    43  }