Home > Backend Development > Golang > Can Go\'s Standard Library Specify a Custom DNS Server for Lookup Functions?

Can Go\'s Standard Library Specify a Custom DNS Server for Lookup Functions?

Susan Sarandon
Release: 2024-11-29 21:58:11
Original
296 people have browsed it

Can Go's Standard Library Specify a Custom DNS Server for Lookup Functions?

Can Go's Lookup Functions Specify a Server?*

Go's dnsclient library seamlessly loads configuration from /etc/resolv.conf, providing essential DNS functionality. However, certain scenarios demand the utilization of a specific DNS server. Does the Go standard library offer a mechanism akin to:

func LookupTXT(name string, dnsServer string) (txt []string, err error)
Copy after login

that can override the default DNS server while maintaining the integrity of /etc/resolv.conf?

Solution

Although the DNS client provided by Go does not directly support specifying a server during DNS resolution, there are alternative approaches to achieve this functionality. One viable option is to leverage the comprehensive dns library developed by miekg:

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)
    }
}
Copy after login

Upon executing this code, you will obtain the resolved IP addresses for the target domain, demonstrating the effective use of a specified DNS server without compromising the system's default configuration.

The above is the detailed content of Can Go\'s Standard Library Specify a Custom DNS Server for Lookup Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template