oasis/dnsmasq/dnsmasq.go
2025-01-19 12:54:21 -05:00

81 lines
1.8 KiB
Go

package dnsmasq
import (
"fmt"
"log"
"net"
"strings"
"github.com/miekg/dns"
)
func Serve() {
// Create a new DNS server
server := &dns.Server{Addr: ":8989", Net: "udp"}
// Set up the handler for DNS requests
dns.HandleFunc(".", handleRequest)
// Start listening for incoming DNS requests
fmt.Println("Listening for DNS requests on port 8989...")
if err := server.ListenAndServe(); err != nil {
log.Fatalf("Failed to start DNS server: %v", err)
}
}
func forward(r *dns.Msg) (*dns.Msg, error) {
// Forward the request to a real DNS server (for example, Google's public DNS server)
client := new(dns.Client)
realDNSAddr := "8.8.8.8:53" // Google's DNS server address
// Send the request to the actual DNS server
response, _, err := client.Exchange(r, realDNSAddr)
if err != nil {
log.Printf("Failed to forward DNS request: %v", err)
return nil, err
}
return response, nil
}
func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
domain := r.Question[0].Name
domain = strings.Trim(domain, ".")
parts := strings.Split(domain, ".")
tld := parts[len(parts)-1]
response := dns.Msg{}
response.SetReply(r)
// Check if it's a query for an A record (IPv4 address)
if "test" == tld {
log.Printf("Handling request for %s", domain)
for _, question := range r.Question {
if question.Qtype == dns.TypeA {
// Create a loopback A record pointing to 127.0.0.1
rr := &dns.A{
Hdr: dns.RR_Header{
Name: question.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 300, // TTL in seconds (5 minutes)
},
A: net.ParseIP("127.0.0.1"), // Loopback address
}
response.Answer = append(response.Answer, rr)
}
}
w.WriteMsg(&response)
return
}
// Send the response back to the original client
resp, err := forward(r)
if err != nil {
panic("We broke boys")
}
w.WriteMsg(resp)
}