This is a simple example of a DNS client implemented in Golang:

package main

import (
    "fmt"
    "net"
    "strings"
)

func main() {
    server := '8.8.8.8:53' // Google DNS server
    domain := 'example.com'

    // create UDP connection to DNS server
    conn, err := net.Dial('udp', server)
    if err != nil {
        fmt.Println('Error connecting to DNS server:', err)
        return
    }
    defer conn.Close()

    // create DNS message
    msg := make([]byte, 0, 512)
    msg = append(msg, 0, 0, // ID
        1, 0, // Flags
        0, 1, // Questions
        0, 0, // Answers
        0, 0, // Authorities
        0, 0, // Additional
    )
    // add domain name to message
    for _, label := range strings.Split(domain, '.') {
        msg = append(msg, byte(len(label)))
        msg = append(msg, label...)
    }
    msg = append(msg, 0) // end of domain name
    // add query type and class to message
    msg = append(msg, 0, 1, // type A
        0, 1, // class IN
    )

    // send DNS message and read response
    _, err = conn.Write(msg)
    if err != nil {
        fmt.Println('Error sending DNS query:', err)
        return
    }
    // read message ID to match response
    response := make([]byte, 512)
    _, err = conn.Read(response)
    if err != nil {
        fmt.Println('Error reading DNS response:', err)
        return
    }
    if response[0] != msg[0] || response[1] != msg[1] {
        fmt.Println('Mismatched message ID')
        return
    }

    // parse response for IP address
    if response[3]&0x0f == 0 {
        fmt.Printf('%s: %d.%d.%d.%d\n', domain, response[12], response[13], response[14], response[15])
    } else {
        fmt.Printf('No IP address found for %s\n', domain)
    }
}

In this example, we use Google DNS server (8.8.8.8) to query the IP address of 'example.com'. We use a UDP connection to send the DNS message and read the response from the server. We use the message ID to match the request and response. Finally, we parse the response to obtain the IP address and print the result.

Golang DNS Client Implementation: A Simple Guide with Example

原文地址: https://www.cveoy.top/t/topic/nr6u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录