Skip to content

Instantly share code, notes, and snippets.

@efrenfuentes
Forked from walm/main.go
Created June 5, 2018 00:53
Show Gist options
  • Save efrenfuentes/6d3079c4b5f8db754be6033eee4b8458 to your computer and use it in GitHub Desktop.
Save efrenfuentes/6d3079c4b5f8db754be6033eee4b8458 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