Home >Backend Development >Golang >How Can I Perform DNS Lookups in Go with a Custom DNS Server?
Many network-related operations rely on DNS lookups to resolve hostnames to IP addresses and other information. Golang provides a set of convenient functions in the net package for performing DNS lookups, including LookupAddr and LookupTXT, which return the corresponding IP addresses or text records for a given hostname.
One limitation of these functions is that they typically rely on the system's resolvers configured in /etc/resolv.conf. While this is sufficient in most cases, there may be instances where you need to specify a specific DNS server to perform the lookup.
Unfortunately, the standard Go library does not currently offer functions like LookupAddrWithServer or LookupTXTWithServer that allow you to specify a custom DNS server. However, there are several third-party libraries that provide this functionality, including the popular github.com/miekg/dns.
The following modified example from the answer given by @holys demonstrates how you can use the miekg/dns library to perform DNS lookups with a specified server:
package main import ( "fmt" "log" "github.com/miekg/dns" ) func main() { target := "example.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) } fmt.Printf("Took %v", t) if len(r.Answer) == 0 { log.Fatal("No results") } for _, ans := range r.Answer { arecord := ans.(*dns.A) fmt.Printf("%s", arecord.A) } }
This example uses the github.com/miekg/dns library to perform an A record lookup for example.com using the specified DNS server at 8.8.8.8. By leveraging third-party libraries like miekg/dns, you can extend the functionality provided by the Go standard library to meet your specific requirements.
The above is the detailed content of How Can I Perform DNS Lookups in Go with a Custom DNS Server?. For more information, please follow other related articles on the PHP Chinese website!