Specifying DNS server for lookup in Go

前端 未结 1 1609
走了就别回头了
走了就别回头了 2021-01-05 05:29

Is there a way to specify which DNS server to use for a name lookup?

Looking at https://golang.org/pkg/net/#LookupHost seems it will use only the local resolver

相关标签:
1条回答
  • 2021-01-05 06:30

    Answer from /u/g-a-c on reddit

    If I'm reading that doc right (maybe not)...

    Create yourself a local Resolver, with a custom Dialer, using the DNS address you want to use (https://golang.org/pkg/net/#Resolver) then use the LookupAddr function of that Resolver?

    edit:

    package main
    
    import (
        "context"
        "net"
        "time"
    )
    
    func main() {
        r := &net.Resolver{
            PreferGo: true,
            Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
                d := net.Dialer{
                    Timeout: time.Millisecond * time.Duration(10000),
                }
                return d.DialContext(ctx, "udp", "8.8.8.8:53")
            },
        }
        ip, _ := r.LookupHost(context.Background(), "www.google.com")
    
        print(ip[0])
    }
    

    This seems to work - on my firewall this shows that my machine is opening connections to Google rather than a local domain controller

    0 讨论(0)
提交回复
热议问题