-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (64 loc) · 1.53 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"os"
"github.com/miekg/dns"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprint(os.Stderr, "Invalid number of parameter.\n Currect usage: dns <name>\n")
os.Exit(1)
}
name := os.Args[1]
answer, err := resolveDNS(name)
if err == nil {
for _, record := range answer {
fmt.Println(record)
}
} else {
fmt.Fprintf(os.Stderr, "Failed to resolve %s\n", name)
os.Exit(1)
}
}
func resolveDNS(name string) ([]dns.RR, error) {
nameserver := "192.168.1.1"
c := new(dns.Client)
for {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(name), dns.TypeA)
// DNS request to IP in nameserver ( dns resolver)
fmt.Printf("Quering %s about %s\n", nameserver, name)
resp, _, err := c.Exchange(m, fmt.Sprintf("%s:53", nameserver))
if err != nil {
return nil, err
}
// Answer Section
if len(resp.Answer) > 0 {
if cname, ok := resp.Answer[0].(*dns.CNAME); ok {
return resolveDNS(cname.Target)
}
return resp.Answer, nil
}
// if additional sections exits, look for in it to find the next-level namesever, if it doesnot error out.
found := false
for _, rr := range resp.Extra {
record, ok := rr.(*dns.A)
if ok {
nameserver = record.A.String()
found = true
break
}
}
if !found {
return nil, fmt.Errorf("break in resolution")
}
if len(resp.Extra) == 0 && len(resp.Ns) != 0 {
ns := resp.Ns[0].(*dns.NS)
nsIP, err := resolveDNS(ns.Ns)
if err != nil {
return nil, fmt.Errorf("break in resolution")
}
nameserver = nsIP[0].(*dns.A).A.String()
}
}
}