Skip to content

Instantly share code, notes, and snippets.

@akkuman
Created April 30, 2020 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkuman/a87a82a7ea22185dc19a107e4ab32041 to your computer and use it in GitHub Desktop.
Save akkuman/a87a82a7ea22185dc19a107e4ab32041 to your computer and use it in GitHub Desktop.
golang官方dns解析与只解析a记录的差距
package main
import (
"context"
"fmt"
"net"
"time"
"github.com/miekg/dns"
)
func main() {
domain := "hacktech.cn"
start1 := time.Now().UnixNano()
aLookupHost(domain)
end1 := time.Now().UnixNano()
fmt.Println((end1-start1)/1e6, "ms")
start2 := time.Now().UnixNano()
goLookupHost(domain)
end2 := time.Now().UnixNano()
fmt.Println((end2-start2)/1e6, "ms")
}
func goLookupHost(domain string) {
resolver := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network string, address string) (net.Conn, error) {
d := net.Dialer{}
return d.DialContext(ctx, "udp", "223.5.5.5:53")
},
}
fmt.Println(resolver.LookupHost(context.Background(), domain))
}
func aLookupHost(domain string) {
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion(domain+".", dns.TypeA)
m.RecursionDesired = true
r, _, err := c.Exchange(m, "223.5.5.5:53")
if err != nil {
return
}
if r.Rcode != dns.RcodeSuccess {
return
}
for _, a := range r.Answer {
if arecord, ok := a.(*dns.A); ok {
fmt.Printf("%s\n", arecord.A.String())
}
}
}
// Output
// > arecord.exe
// 185.199.111.153
// 185.199.108.153
// 185.199.110.153
// 185.199.109.153
// 9 ms
// [185.199.111.153 185.199.109.153 185.199.108.153 185.199.110.153 185.199.111.153 185.199.109.153 185.199.108.153 185.199.110.153] <nil>
// 16133 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment