-
Notifications
You must be signed in to change notification settings - Fork 2
/
nameserver.go
62 lines (55 loc) · 1.25 KB
/
nameserver.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
package nameserver
import (
"errors"
"fmt"
"net"
)
// Nameserver handles DNS queries
type Nameserver struct {
Addr *net.UDPAddr
ucon *net.UDPConn
}
// Connect will begin listening for DNS queries on localhost:8853
func (n *Nameserver) Connect() error {
c, err := net.ListenUDP("udp", n.Addr)
if err != nil {
return fmt.Errorf("unable to connect: %s", err.Error())
}
n.ucon = c
return nil
}
// Serve will begin listening for DNS queries and responses
func (n *Nameserver) Serve() error {
if n.ucon == nil {
return errors.New("not connected: must successfully connect with nameserver.Connect first")
}
defer n.teardown()
for {
b := make([]byte, 512)
_, retAddr, err := n.ucon.ReadFromUDP(b)
if err != nil {
return err
}
serializedResponse := respondTo(b)
n.reply(serializedResponse, retAddr)
}
}
func (n *Nameserver) reply(serializedResponse []byte, retAddr *net.UDPAddr) {
_, err := n.ucon.WriteTo(serializedResponse, retAddr)
if err != nil {
fmt.Printf("err: %s\n", err.Error())
}
}
func (n *Nameserver) teardown() error {
if n.ucon != nil {
return n.ucon.Close()
}
return nil
}
func respondTo(b []byte) []byte {
msg := &message{}
_ = msg.deserialize(b)
response := msg.response()
sr, _ := response.serialize()
return sr
}