Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying DNS server for lookup in Go

Tags:

go

dns

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

LookupHost looks up the given host using the local resolver. It returns a slice 
of that host's addresses.

Also earlier on that link

 It can use a pure Go resolver that sends DNS requests directly to 
 the servers listed in /etc/resolv.conf,

How could one do a lookup against arbitrary servers like one can do with dig?

dig @8.8.8.8 google.com
like image 512
Francisco1844 Avatar asked Jan 24 '20 03:01

Francisco1844


People also ask

How do I do a DNS lookup?

Access your command prompt. Use the command nslookup (this stands for Name Server Lookup) followed by the domain name or IP address you want to trace. Press enter. This command will simply query the Name Service for information about the specified IP address or domain name.

What are the two types of DNS lookup that can be performed?

3 types of DNS queries—recursive, iterative, and non-recursive.


1 Answers

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, network, "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

like image 75
Francisco1844 Avatar answered Oct 17 '22 06:10

Francisco1844