Home > Backend Development > Golang > How to Perform a LookupTXT in Golang Without Changing /etc/resolv.conf?

How to Perform a LookupTXT in Golang Without Changing /etc/resolv.conf?

Patricia Arquette
Release: 2024-12-03 12:58:11
Original
294 people have browsed it

How to Perform a LookupTXT in Golang Without Changing /etc/resolv.conf?

LookupTXT Function in Golang without Modifying /etc/resolv.conf

The standard Golang library does not provide a direct function equivalent to LookupTXT that allows specifying a custom DNS server. The reason for this is that the DNS client relies on the configuration from /etc/resolv.conf for DNS server information.

However, there are several options to achieve what you need while adhering to the requirement of not modifying /etc/resolv.conf.

Using a Custom DNS Resolver:

One approach is to use a custom DNS resolver library that supports specifying a specific DNS server. For example, the github.com/miekg/dns library provides the flexibility to set a custom server IP in the dns.Client object. The following code demonstrates how to use this library:

import (
    "log"
    "net"

    "github.com/miekg/dns"
)

func main() {
    target := "microsoft.com"
    server := "8.8.8.8"

    // Create a new DNS client with a custom server.
    c := dns.Client{Net: "udp", Server: server}

    // Build a request message.
    m := dns.Msg{}
    m.SetQuestion(target+".", dns.TypeTXT)

    // Exchange the request and receive the response.
    r, _, err := c.Exchange(&m, server+":53")
    if err != nil {
        log.Fatal(err)
    }

    // Process the response.
    if len(r.Answer) == 0 {
        log.Fatal("No results")
    }
    for _, ans := range r.Answer {
        TXTrecord := ans.(*dns.TXT)
        for _, txt := range TXTrecord.Txt {
            log.Println(txt)
        }
    }
}
Copy after login

The above is the detailed content of How to Perform a LookupTXT in Golang Without Changing /etc/resolv.conf?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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