--- /net/dnsconfig_unix.go 2016-08-20 08:14:05.763235602 -0400 +++ /net/dnsconfig_unix.go 2016-08-20 08:14:05.763235602 -0400 @@ -9,15 +9,58 @@ package net import ( + "fmt" "os" + "os/exec" + "strings" "time" ) var ( - defaultNS = []string{"127.0.0.1:53", "[::1]:53"} + currentNS []string getHostname = os.Hostname // variable for testing ) +func getDefaultNS() []string { + var servers []string + for _, prop := range []string{"net.dns1", "net.dns2"} { + cmd := exec.Command("getprop", prop) + outputBytes, err := cmd.Output() + if err != nil { + continue + } + output := strings.Trim(string(outputBytes), "\n") + if ParseIP(output) != nil { + servers = append(servers, output + ":53") + } + } + + if len(servers) == 0 { + servers = []string{"8.8.8.8:53", "8.8.4.4:53", "4.2.2.1:53"} + } + + if !slicesEqual(currentNS, servers) { + fmt.Println("Using DNS servers:", servers) + currentNS = servers + } + + return currentNS +} + +func slicesEqual(a, b []string) bool { + if len(a) != len(b) { + return false + } + + for i := range a { + if a[i] != b[i] { + return false + } + } + + return true +} + type dnsConfig struct { servers []string // server addresses (in host:port form) to use search []string // rooted suffixes to append to local name @@ -40,7 +83,7 @@ } file, err := open(filename) if err != nil { - conf.servers = defaultNS + conf.servers = getDefaultNS() conf.search = dnsDefaultSearch() conf.err = err return conf @@ -49,7 +92,7 @@ if fi, err := file.file.Stat(); err == nil { conf.mtime = fi.ModTime() } else { - conf.servers = defaultNS + conf.servers = getDefaultNS() conf.search = dnsDefaultSearch() conf.err = err return conf @@ -126,7 +169,7 @@ } } if len(conf.servers) == 0 { - conf.servers = defaultNS + conf.servers = getDefaultNS() } if len(conf.search) == 0 { conf.search = dnsDefaultSearch()