/
address.go
78 lines (63 loc) · 1.17 KB
/
address.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
package main
import (
"io/ioutil"
"net"
"net/http"
"strings"
)
var (
privateRanges = []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}
)
func getLocalAddresses() ([]net.IP, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
privates := make([]net.IPNet, 0, len(privateRanges))
for _, s := range privateRanges {
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
panic(err)
}
privates = append(privates, *ipnet)
}
result := make([]net.IP, 0, 5)
addrLoop:
for _, a := range addrs {
var ip net.IP
if ipaddr, ok := a.(*net.IPAddr); ok {
ip = ipaddr.IP
}
if ipnet, ok := a.(*net.IPNet); ok {
ip = ipnet.IP
}
if !ip.IsGlobalUnicast() {
continue
}
for _, n := range privates {
if n.Contains(ip) {
continue addrLoop
}
}
result = append(result, ip)
}
return result, nil
}
func getNATAddress() (net.IP, error) {
resp, err := http.Get("http://ipecho.net/plain")
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
ip := net.ParseIP(strings.TrimSpace(string(data)))
return ip, nil
}