dns.go 868 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "net"
  6. "strings"
  7. "time"
  8. )
  9. type dnsSmartClient struct {
  10. dialer *net.Dialer
  11. }
  12. func newDnsSmartClient() *dnsSmartClient {
  13. return &dnsSmartClient{
  14. dialer: &net.Dialer{
  15. Timeout: 3 * time.Second,
  16. KeepAlive: 30 * time.Second,
  17. DualStack: true,
  18. },
  19. }
  20. }
  21. func (c *dnsSmartClient) Dial(ctx context.Context, network, address string) (conn net.Conn, err error) {
  22. // net.dns1 might be ipv6, Issue https://github.com/openatx/atx-agent/issues/39
  23. dns1 := getProperty("net.dns1")
  24. if dns1 == "" || strings.Contains(dns1, ":") {
  25. // 国内DNS列表: https://www.zhihu.com/question/32229915
  26. dns1 = "114.114.114.114"
  27. }
  28. log.Println("dns resolve", dns1)
  29. return c.dialer.DialContext(ctx, "udp", dns1+":53")
  30. }
  31. func init() {
  32. net.DefaultResolver = &net.Resolver{
  33. PreferGo: true,
  34. Dial: newDnsSmartClient().Dial,
  35. }
  36. }