-
Notifications
You must be signed in to change notification settings - Fork 0
/
packet.go
92 lines (77 loc) · 1.79 KB
/
packet.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
type DnsPacket struct {
header DnsHeader
questions []DnsQuestion
answers []DnsRecord
authorities []DnsRecord
resources []DnsRecord
}
// NewDnsPacket creates a new DnsPacket
func NewDnsPacket() *DnsPacket {
return &DnsPacket{}
}
// read reads a packet from the buffer
func (d *DnsPacket) fromBuffer(buf *BytePacketBuffer) error {
if err := d.header.read(buf); err != nil {
return err
}
for i := 0; i < int(d.header.questions); i++ {
q := DnsQuestion{}
if err := q.read(buf); err != nil {
return err
}
d.questions = append(d.questions, q)
}
for i := 0; i < int(d.header.answers); i++ {
r := DnsRecord{}
if err := r.read(buf); err != nil {
return err
}
d.answers = append(d.answers, r)
}
for i := 0; i < int(d.header.authoritativeEntries); i++ {
r := DnsRecord{}
if err := r.read(buf); err != nil {
return err
}
d.authorities = append(d.authorities, r)
}
for i := 0; i < int(d.header.resourceEntries); i++ {
r := DnsRecord{}
if err := r.read(buf); err != nil {
return err
}
d.resources = append(d.resources, r)
}
return nil
}
func (d *DnsPacket) write(buf *BytePacketBuffer) error {
d.header.questions = uint16(len(d.questions))
d.header.answers = uint16(len(d.answers))
d.header.authoritativeEntries = uint16(len(d.authorities))
d.header.resourceEntries = uint16(len(d.resources))
if err := d.header.write(buf); err != nil {
return err
}
for _, q := range d.questions {
if err := q.write(buf); err != nil {
return err
}
}
for _, a := range d.answers {
if err := a.write(buf); err != nil {
return err
}
}
for _, a := range d.authorities {
if err := a.write(buf); err != nil {
return err
}
}
for _, a := range d.resources {
if err := a.write(buf); err != nil {
return err
}
}
return nil
}