-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
74 lines (64 loc) · 1.32 KB
/
server.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
package main
import (
"errors"
"fmt"
"github.com/miekg/dns"
"net"
"os"
"os/exec"
"strings"
)
func main() {
addr := "127.0.0.1:8053"
if len(os.Args) > 1 {
addr = os.Args[1]
}
dns.HandleFunc("docker.local", SimpleHandler)
server := &dns.Server{Addr: addr, Net: "udp"}
fmt.Printf("running server on %s\n", addr)
err := server.ListenAndServe()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func SimpleHandler(w dns.ResponseWriter, req *dns.Msg) {
m := new(dns.Msg)
m.SetReply(req)
m.Authoritative = true
fqdn := req.Question[0].Name
fmt.Printf("resolving %s\n", req.Question[0].Name)
split := strings.Split(fqdn, ".")
if len(split) != 4 {
w.WriteMsg(m)
return
}
name := split[0]
ip, err := GetContainerIp(name)
if err != nil {
fmt.Print(err)
w.WriteMsg(m)
return
}
ip = strings.TrimSpace(ip)
fmt.Printf("%s resolves to %s\n", fqdn, ip)
a := &dns.A{
Hdr: dns.RR_Header{
Name: fqdn,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 0,
},
A: net.ParseIP(ip).To4(),
}
m.Answer = append(m.Answer, a)
w.WriteMsg(m)
}
func GetContainerIp(name string) (string, error) {
cmd := exec.Command("docker", "inspect", "-f", "{{ .NetworkSettings.IPAddress }}", name)
out, err := cmd.CombinedOutput()
if err != nil {
return "", errors.New(string(out))
}
return string(out), nil
}