-
Notifications
You must be signed in to change notification settings - Fork 1
/
dnscache.go
79 lines (66 loc) · 1.21 KB
/
dnscache.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
package main
import (
"fmt"
"net"
"strings"
"sync"
)
var (
dnsCache = make(map[string]string, 0)
dnsCacheLock sync.RWMutex
)
func resolveDomain(domain string) (string, error) {
var host string
var port string
var ip string
var ok bool
var err error
if strings.Contains(domain, ":") {
host, port, err = net.SplitHostPort(domain)
if err != nil {
return "", err
}
} else {
host = domain
}
if isIp := net.ParseIP(host); isIp != nil {
return domain, nil
}
dnsCacheLock.RLock()
{
ip, ok = dnsCache[host]
}
dnsCacheLock.RUnlock()
if !ok {
ips, err := net.LookupIP(host)
if err != nil {
return "", err
}
if len(ips) == 0 {
return "", fmt.Errorf("failed to lookup %s", host)
}
// If it's an ipv6 address we need brackets around it.
if ipv4 := ips[0].To4(); ipv4 != nil {
ip = ipv4.String()
} else {
ip = "[" + ips[0].String() + "]"
}
dnsCacheLock.Lock()
{
dnsCache[host] = ip
}
dnsCacheLock.Unlock()
}
if port != "" {
return ip + ":" + port, nil
} else {
return ip, nil
}
}
func cacheDial(network string, addr string) (net.Conn, error) {
url, err := resolveDomain(addr)
if err != nil {
return nil, err
}
return net.Dial(network, url)
}