Skip to content

Instantly share code, notes, and snippets.

@TimothyYe
Forked from walm/main.go
Created September 30, 2017 08:23
Show Gist options
  • Save TimothyYe/5b99bd8b08efbf31e95e5e256f4fef5a to your computer and use it in GitHub Desktop.
Save TimothyYe/5b99bd8b08efbf31e95e5e256f4fef5a to your computer and use it in GitHub Desktop.
Simple Golang DNS Server
package main
import (
"fmt"
"log"
"strconv"
"github.com/miekg/dns"
)
var records = map[string]string{
"test.service.": "192.168.0.2",
}
func parseQuery(m *dns.Msg) {
for _, q := range m.Question {
switch q.Qtype {
case dns.TypeA:
log.Printf("Query for %s\n", q.Name)
ip := records[q.Name]
if ip != "" {
rr, err := dns.NewRR(fmt.Sprintf("%s A %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("service.", handleDnsRequest)
// start server
port := 5353
server := &dns.Server{Addr: ":" + strconv.Itoa(port), Net: "udp"}
log.Printf("Starting at %d\n", port)
err := server.ListenAndServe()
defer server.Shutdown()
if err != nil {
log.Fatalf("Failed to start server: %s\n ", err.Error())
}
}
dig @localhost -p 5353 test.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment