...
1
2
3
4
5 package dnsmessage_test
6
7 import (
8 "fmt"
9 "net"
10 "strings"
11
12 "golang.org/x/net/dns/dnsmessage"
13 )
14
15 func ExampleParser() {
16 msg := dnsmessage.Message{
17 Header: dnsmessage.Header{Response: true, Authoritative: true},
18 Questions: []dnsmessage.Question{
19 {
20 Name: dnsmessage.MustNewName("foo.bar.example.com."),
21 Type: dnsmessage.TypeA,
22 Class: dnsmessage.ClassINET,
23 },
24 {
25 Name: dnsmessage.MustNewName("bar.example.com."),
26 Type: dnsmessage.TypeA,
27 Class: dnsmessage.ClassINET,
28 },
29 },
30 Answers: []dnsmessage.Resource{
31 {
32 Header: dnsmessage.ResourceHeader{
33 Name: dnsmessage.MustNewName("foo.bar.example.com."),
34 Type: dnsmessage.TypeA,
35 Class: dnsmessage.ClassINET,
36 },
37 Body: &dnsmessage.AResource{A: [4]byte{127, 0, 0, 1}},
38 },
39 {
40 Header: dnsmessage.ResourceHeader{
41 Name: dnsmessage.MustNewName("bar.example.com."),
42 Type: dnsmessage.TypeA,
43 Class: dnsmessage.ClassINET,
44 },
45 Body: &dnsmessage.AResource{A: [4]byte{127, 0, 0, 2}},
46 },
47 },
48 }
49
50 buf, err := msg.Pack()
51 if err != nil {
52 panic(err)
53 }
54
55 wantName := "bar.example.com."
56
57 var p dnsmessage.Parser
58 if _, err := p.Start(buf); err != nil {
59 panic(err)
60 }
61
62 for {
63 q, err := p.Question()
64 if err == dnsmessage.ErrSectionDone {
65 break
66 }
67 if err != nil {
68 panic(err)
69 }
70
71 if q.Name.String() != wantName {
72 continue
73 }
74
75 fmt.Println("Found question for name", wantName)
76 if err := p.SkipAllQuestions(); err != nil {
77 panic(err)
78 }
79 break
80 }
81
82 var gotIPs []net.IP
83 for {
84 h, err := p.AnswerHeader()
85 if err == dnsmessage.ErrSectionDone {
86 break
87 }
88 if err != nil {
89 panic(err)
90 }
91
92 if (h.Type != dnsmessage.TypeA && h.Type != dnsmessage.TypeAAAA) || h.Class != dnsmessage.ClassINET {
93 continue
94 }
95
96 if !strings.EqualFold(h.Name.String(), wantName) {
97 if err := p.SkipAnswer(); err != nil {
98 panic(err)
99 }
100 continue
101 }
102
103 switch h.Type {
104 case dnsmessage.TypeA:
105 r, err := p.AResource()
106 if err != nil {
107 panic(err)
108 }
109 gotIPs = append(gotIPs, r.A[:])
110 case dnsmessage.TypeAAAA:
111 r, err := p.AAAAResource()
112 if err != nil {
113 panic(err)
114 }
115 gotIPs = append(gotIPs, r.AAAA[:])
116 }
117 }
118
119 fmt.Printf("Found A/AAAA records for name %s: %v\n", wantName, gotIPs)
120
121
122
123
124 }
125
View as plain text