discordBots/cmd/domaincheckbot/dns/domain.go
2024-07-16 20:09:46 +00:00

75 lines
1.5 KiB
Go

package dns
import (
"fmt"
"github.com/miekg/dns"
"net"
"slices"
"strings"
)
type Domain struct {
Name string
NS []string
}
func CheckDomain(domain, tld string) Domain {
nameservers := []string{}
// Create a new DNS message
m := new(dns.Msg)
// Set the question section of the message with the domain and query type
m.SetQuestion(dns.Fqdn(fmt.Sprintf("%v.%v", domain, tld)), dns.TypeNS)
// Create a DNS client
c := new(dns.Client)
// Define the .com TLD server
ns, err := net.LookupNS(tld)
if err != nil {
return Domain{
Name: domain + "." + tld,
NS: nameservers,
}
}
var tldServer string
if len(ns) > 0 {
tldServer = strings.Trim(ns[0].Host, ".") + ":53"
} else {
//log.Fatalf("Could not resolve %v", tld)
return Domain{
Name: domain + "." + tld,
NS: nameservers,
}
}
// Send the DNS query to the TLD server
r, _, err := c.Exchange(m, tldServer)
if err != nil {
//log.Fatalf("Failed to query the TLD server: %v", err)
return Domain{
Name: domain + "." + tld,
NS: nameservers,
}
}
// Check for response errors
if r.Rcode != dns.RcodeSuccess {
//log.Fatalf("Failed to get a valid response: %v", r.Rcode)
return Domain{
Name: domain + "." + tld,
NS: nameservers,
}
}
// Print the nameservers from the response
for _, ans := range r.Ns {
if ns, ok := ans.(*dns.NS); ok {
nameservers = append(nameservers, strings.ToLower(ns.Ns))
}
}
slices.Sort(nameservers)
return Domain{
Name: domain + "." + tld,
NS: nameservers,
}
}