如何使用GO更新DNS记录

时间:2019-06-26 17:09:36

标签: go dns ip

我需要在GO中编写一些代码来动态更新DNS条目。我尝试遵循此documentation 我对GO和DNS的经验很少,所以请原谅我对以下代码无法正常工作的无知。它确实可以成功运行,并显示“ SUCCESS”(成功),什么也没有。

我期望以下代码将在DNS中创建一个“ A记录”,其主机名为“ boring.zone.example.com”,指向IP地址“ 172.16.254.1”(注意:主机名和IP均已此帖子已更改)

package main

import (
    "fmt"
    "github.com/miekg/dns"
    "log"
    "net"
    "strconv"
)

// Setup client
var config, _ = dns.ClientConfigFromFile("/etc/resolv.conf")
var address = net.JoinHostPort(config.Servers[0], config.Port)
var client = new(dns.Client)

func main() {

    updateDNS("172.16.254.1", "zone.example.com", "boring.zone.example.com");
}

// see: https://godoc.org/github.com/miekg/dns
func updateDNS(ip string, zone string, hostname string) error {

    record := &dns.A{
        Hdr: dns.RR_Header{Name: dns.Fqdn(hostname), Rrtype:dns.TypeA, Class:dns.ClassINET, Ttl:60},
        A: net.ParseIP(ip),
    }
    records := []dns.RR{record}

    msg := new(dns.Msg)
    // Question defines the zone
    msg.SetQuestion(dns.Fqdn(zone), dns.TypeANY)
    // Prerequisite
    //msg.NameNotUsed(records) // FIXME this fails
    // Updates to be made
    msg.Insert(records)

    // Send message to DNS
    response, _, err := client.Exchange(msg, address)

    if err != nil {
        log.Fatalf("error: %s\n", err.Error())
    }

    switch response.Rcode {
    case dns.RcodeSuccess:
        fmt.Print("SUCCESS\n")
    case dns.RcodeFormatError:
        log.Fatalf("FormErr   - Format Error")
    case dns.RcodeNameError:
        log.Fatalf("NXDomain  - Non-Existent Domain")
    default:
        log.Fatalf("invalid " + strconv.Itoa(response.Rcode))
    }

    for _, a := range response.Answer {
        fmt.Printf("%v\n", a)
    }

    return err
}

0 个答案:

没有答案