Last active
November 5, 2024 16:22
-
-
Save walm/0d67b4fb2d5daf3edd4fad3e13b162cb 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 |
@Ran-Xing I used the dig
command.
oh,no,dig work, but system not work,you can try set 127.0.0.1 on system, then run
get ipaddress
docker run -itd --name nginx --rm nginx
docker run -itd --name ubuntu --rm ubuntu bash
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nginx
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ubuntu
records add
"nginx.service.": {"192.168.0.2"},
"ubuntu.service.": {"192.168.0.2"},
at last
set word_system dns
127.0.0.1
nslookup nginx.service
curl nginx.service -v
@NinoM4ster I also wrote a dns server according to this writing method, which supports A records, but it does not work on macOS and Linux
dig works fine
oh, in my case I'm not using this as a system-wide DNS server, but using a service to query it directly.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
127.0.0.1:53
curl nslookup