/
ip.go
69 lines (60 loc) · 1.38 KB
/
ip.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
package iptools
import (
"net"
"strings"
)
// Ranges of addresses allocated by IANA for private internets, as per RFC1918.
var PrivateNetworks = []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
}
// GetHostIPs returns a list of IP addresses of all host's interfaces.
func GetHostIPs() ([]net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
var ips []net.IP
for _, iface := range ifaces {
if strings.HasPrefix(iface.Name, "docker") {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok {
ips = append(ips, ipnet.IP)
}
}
}
return ips, nil
}
// GetPrivateHostIPs returns a list of host's private IP addresses.
func GetPrivateHostIPs() ([]net.IP, error) {
ips, err := GetHostIPs()
if err != nil {
return nil, err
}
var privateIPs []net.IP
for _, ip := range ips {
// skip loopback, non-IPv4 and non-private addresses
if ip.IsLoopback() || ip.To4() == nil || !IsPrivate(ip) {
continue
}
privateIPs = append(privateIPs, ip)
}
return privateIPs, nil
}
// IsPrivate determines whether a passed IP address is from one of private blocks or not.
func IsPrivate(ip net.IP) bool {
for _, network := range PrivateNetworks {
_, ipnet, _ := net.ParseCIDR(network)
if ipnet.Contains(ip) {
return true
}
}
return false
}