Skip to content

Instantly share code, notes, and snippets.

@NinoM4ster
Created November 11, 2022 03:54
Show Gist options
  • Save NinoM4ster/edaac29339371c6dde7cdb48776d2854 to your computer and use it in GitHub Desktop.
Save NinoM4ster/edaac29339371c6dde7cdb48776d2854 to your computer and use it in GitHub Desktop.
Golang DNS server with multiple A/SRV records
package main
import (
"fmt"
"log"
"github.com/miekg/dns"
)
// adapted from https://gist.github.com/walm/0d67b4fb2d5daf3edd4fad3e13b162cb
// to support multiple A records (different IPs) and multiple SRV records (same host, different ports).
// dig @localhost -p 5353 test.service
var records = map[string][]string{
"test.service.": {
"192.168.0.2",
"192.168.0.3",
"192.168.0.4",
"192.168.0.5",
},
}
// dig @localhost -p 5353 _api._tcp.localhost SRV
var srvRecords = map[string][]string{
"_api._tcp.localhost.": {
"10 5 8080 localhost",
"10 5 8081 localhost",
"10 5 8082 localhost",
"10 5 8083 localhost",
},
}
func parseQuery(m *dns.Msg) {
for _, q := range m.Question {
log.Printf("Query for %s\n", q.Name)
switch q.Qtype {
case dns.TypeA:
ips := records[q.Name]
if len(ips) > 0 {
for _, ip := range ips {
rr, err := dns.NewRR(fmt.Sprintf("%s A %s", q.Name, ip))
if err == nil {
m.Answer = append(m.Answer, rr)
}
}
}
case dns.TypeSRV:
ips := srvRecords[q.Name]
if len(ips) > 0 {
for _, ip := range ips {
rr, err := dns.NewRR(fmt.Sprintf("%s SRV %s", q.Name, ip))
if err == nil {
m.Answer = append(m.Answer, rr)
}
}
}
}
}
}
func handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
m.Compress = false
switch r.Opcode {
case dns.OpcodeQuery:
parseQuery(m)
}
w.WriteMsg(m)
}
func main() {
// attach request handler func
dns.HandleFunc(".", handleDnsRequest)
// start server
server := &dns.Server{Addr: ":5353", Net: "udp"}
log.Printf("Starting at %s\n", server.Addr)
err := server.ListenAndServe()
if err != nil {
log.Fatalf("Failed to start server: %s\n ", err.Error())
}
defer server.Shutdown()
}
@Ran-Xing
Copy link

Please use port 53 and add DNS 127.0.0.7 to the system.Then you can try nslookup or curl.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment