-
-
Save r6m/d20a45b5cf3428676217248aab16425c to your computer and use it in GitHub Desktop.
Simple Golang DNS Server
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" | |
"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()) | |
} | |
} |
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
dig @localhost -p 5353 test.service |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment