Home >Backend Development >Golang >How to Specify a Custom DNS Server for DNS Lookups in Go?

How to Specify a Custom DNS Server for DNS Lookups in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 05:06:10764browse

How to Specify a Custom DNS Server for DNS Lookups in Go?

Lookup Function Alternatives in Golang for Custom DNS Server Specification

The Go standard library does not currently offer a function similar to LookupTXT(name, dnsServer) that allows users to specify a custom DNS server when performing DNS lookups. The Lookup*. functions available in the standard library solely rely on the configuration provided in /etc/resolv.conf.

If you require the flexibility of specifying a custom DNS server, consider utilizing third-party libraries such as github.com/miekg/dns. This library provides a lightweight and comprehensive set of functions for performing DNS lookups, including the ability to specify a custom DNS server. An example of using github.com/miekg/dns to perform a DNS lookup with a custom DNS server is provided below:

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)
    }
}

The above is the detailed content of How to Specify a Custom DNS Server for DNS Lookups in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn