-
-
Save walm/0d67b4fb2d5daf3edd4fad3e13b162cb to your computer and use it in GitHub Desktop.
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 |
To respond with NXDOMAIN (non-existant domain), the following should be called:
m.SetRcode(r, dns.RcodeNameError)
How do I get the client IP address?
It seems you can get it via
dns.Responsewriter.RemoteAddr()
nslookup test.service
;; Got recursion not available from 127.0.0.1, trying next server
Server: 8.8.8.8
Address: 8.8.8.8#53
** server can't find test.service: NXDOMAIN
I made a version that supports multiple A records (and also multiple SRV records): https://gist.github.com/NinoM4ster/edaac29339371c6dde7cdb48776d2854
@NinoM4ster Are you interested in communicating with dns servers?
@NinoM4ster Are you interested in communicating with dns servers?
I'm not sure what you mean.
127.0.0.1:53
curl nslookup
@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.
muchos gracias!