添加一个冗余 DNS 服务器

This commit is contained in:
naiba 2021-05-27 21:10:39 +08:00
parent 2b05dcfc23
commit 5ed0e6a587

View File

@ -9,6 +9,7 @@ import (
"net" "net"
"net/http" "net/http"
"strings" "strings"
"sync"
"time" "time"
"github.com/miekg/dns" "github.com/miekg/dns"
@ -108,31 +109,49 @@ func resolveIP(addr string, ipv6 bool) (string, error) {
} }
m.RecursionDesired = true m.RecursionDesired = true
dnsServer := "2606:4700:4700::1111" dnsServers := []string{"2606:4700:4700::1001", "2001:4860:4860::8844"}
if !ipv6 { if !ipv6 {
dnsServer = "1.1.1.1" dnsServers = []string{"1.0.0.1", "8.8.4.4"}
}
c := new(dns.Client)
r, _, err := c.Exchange(m, net.JoinHostPort(dnsServer, "53"))
if err != nil {
return "", err
} }
var wg sync.WaitGroup
var resolveLock sync.RWMutex
var ipv4Resolved, ipv6Resolved bool var ipv4Resolved, ipv6Resolved bool
for _, ans := range r.Answer {
if ipv6 { wg.Add(len(dnsServers))
if aaaa, ok := ans.(*dns.AAAA); ok { for i := 0; i < len(dnsServers); i++ {
url[0] = "[" + aaaa.AAAA.String() + "]" go func(i int) {
ipv6Resolved = true defer wg.Done()
c := new(dns.Client)
c.Timeout = time.Second * 3
r, _, err := c.Exchange(m, net.JoinHostPort(dnsServers[i], "53"))
if err != nil {
return
} }
} else { resolveLock.Lock()
if a, ok := ans.(*dns.A); ok { defer resolveLock.Unlock()
url[0] = a.A.String() if ipv6 && ipv6Resolved {
ipv4Resolved = true return
} }
} if !ipv6 && ipv4Resolved {
return
}
for _, ans := range r.Answer {
if ipv6 {
if aaaa, ok := ans.(*dns.AAAA); ok {
url[0] = "[" + aaaa.AAAA.String() + "]"
ipv6Resolved = true
}
} else {
if a, ok := ans.(*dns.A); ok {
url[0] = a.A.String()
ipv4Resolved = true
}
}
}
}(i)
} }
wg.Wait()
if ipv6 && !ipv6Resolved { if ipv6 && !ipv6Resolved {
return "", errors.New("the AAAA record not resolved") return "", errors.New("the AAAA record not resolved")