resolvconf_unix.go 911 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // +build linux darwin
  2. package resolvconf
  3. import (
  4. "bufio"
  5. "io"
  6. "os"
  7. "strings"
  8. )
  9. const (
  10. resolvConfPath = "/etc/resolv.conf"
  11. )
  12. // ParseResolvConf parse /etc/resolv.conf file and return nameservers
  13. func ParseResolvConf() ([]string, error) {
  14. fp, err := os.Open(resolvConfPath)
  15. if err != nil {
  16. return nil, err
  17. }
  18. defer fp.Close()
  19. return parse(fp)
  20. }
  21. func parse(fp io.Reader) ([]string, error) {
  22. var result []string
  23. bufRd := bufio.NewReader(fp)
  24. for {
  25. line, err := bufRd.ReadString('\n')
  26. if err != nil {
  27. if err != io.EOF {
  28. return nil, err
  29. }
  30. if line == "" {
  31. break
  32. }
  33. }
  34. line = strings.TrimSpace(line)
  35. // ignore comment, comment startwith #
  36. if strings.HasPrefix(line, "#") {
  37. continue
  38. }
  39. fields := strings.Fields(line)
  40. if len(fields) < 2 {
  41. continue
  42. }
  43. if fields[0] == "nameserver" {
  44. result = append(result, fields[1:]...)
  45. }
  46. }
  47. return result, nil
  48. }