Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why golang Lookup*** function can't provide a server parameter?

Tags:

go

dns

nslookup

For nslookup command, it has nslookup somewhere.com some.dns.server.

However, it seems that golang dnsclient only load config from /etc/resolv.conf

code here: https://golang.org/src/net/dnsclient_unix.go#L225

Does the golang standard library provide something like func LookupTXT(name string, dnsServer string) (txt []string, err error) ?

requirement: 1. Don't change the default /etc/resolv.conf.

like image 342
holys Avatar asked May 05 '15 02:05

holys


2 Answers

@holys

"github.com/miekg/dns is too heavy for me"

It's not that heavy:

package main

import (
    "log"

    "github.com/miekg/dns"
)

func main() {

    target := "microsoft.com"
    server := "8.8.8.8"

    c := dns.Client{}
    m := dns.Msg{}
    m.SetQuestion(target+".", dns.TypeA)
    r, t, err := c.Exchange(&m, server+":53")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Took %v", t)
    if len(r.Answer) == 0 {
        log.Fatal("No results")
    }
    for _, ans := range r.Answer {
        Arecord := ans.(*dns.A)
        log.Printf("%s", Arecord.A)
    }
}

When run, you should see:

$ go run dns.go
2015/07/26 00:24:46 Took 16.138928ms
2015/07/26 00:24:46 134.170.188.221
2015/07/26 00:24:46 134.170.185.46
like image 181
jpillora Avatar answered Oct 22 '22 09:10

jpillora


@holys

You can use this simple dns_resolver based on miekg/dns

go get github.com/bogdanovich/dns_resolver
package main

import (
    "log"
    "github.com/bogdanovich/dns_resolver"
)

func main() {
    resolver := dns_resolver.New([]string{"8.8.8.8", "8.8.4.4"})

    // In case of i/o timeout
    resolver.RetryTimes = 5

    ip, err := resolver.LookupHost("google.com")
    if err != nil {
        log.Fatal(err.Error())
    }
    log.Println(ip)
    // Output [216.58.192.46]
}
like image 12
Anton Avatar answered Oct 22 '22 10:10

Anton