Created
November 11, 2022 03:54
-
-
Save NinoM4ster/edaac29339371c6dde7cdb48776d2854 to your computer and use it in GitHub Desktop.
Golang DNS server with multiple A/SRV records
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please use port 53 and add DNS 127.0.0.7 to the system.Then you can try nslookup or curl.