Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example code #3

Closed
Ran-Xing opened this issue Oct 29, 2022 · 0 comments
Closed

example code #3

Ran-Xing opened this issue Oct 29, 2022 · 0 comments

Comments

@Ran-Xing
Copy link
Collaborator

package main

import (
	"github.com/miekg/dns"
	log "github.com/sirupsen/logrus"
	"net"
	"strconv"
	"strings"
)

var records = map[string]string{
	"test.service": "192.168.0.2",
}

func handleDnsRequest(w dns.ResponseWriter, m *dns.Msg) {
	r := new(dns.Msg)
	r.SetReply(m)
	r.Compress = true
	r.Authoritative = true
	r.RecursionAvailable = true
	IPAddress := "NULL"
	Domain := strings.TrimRight(r.Question[0].Name, ".")

	defer func(w dns.ResponseWriter, msg *dns.Msg) {
		log.Infof("Query: [%v ? %s --> %v]\n", w.RemoteAddr(), Domain, IPAddress)
		err := w.WriteMsg(msg)
		if err != nil {
			log.Errorf("Error writing response: %v", err)
			return
		}
	}(w, r)

	// not resolve
	if r.Question[0].Qtype != dns.TypeA {
		r.Rcode = dns.RcodeNotImplemented
		return
	}
	if addr := records[Domain]; addr != "" {
		IPAddress = addr
		r.Answer = append(r.Answer, &dns.A{
			Hdr: dns.RR_Header{
				Name:   m.Question[0].Name,
				Rrtype: dns.TypeA,
				Class:  dns.ClassINET,
				Ttl:    uint32(86400),
			},
			A: net.ParseIP(IPAddress).To4(),
		})
	}

	if len(r.Answer) == 0 {
		r.Rcode = dns.RcodeNameError
	}
}

func main() {
	// attach request handler func
	dns.HandleFunc("service.", handleDnsRequest)

	// start server
	port := 53
	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())
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant