-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalip.go
67 lines (57 loc) · 1.25 KB
/
localip.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
package gostream
import (
"errors"
"net"
)
// from https://gist.github.com/miguelmota/8544989558d8723b42068aec5bc72ebf
// LocalIP get the host machine local IP address
func LocalIP() (net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
// Filter for enX or ethX or wlanX
if iface.Name[0] != 'e' && iface.Name[0] != 'w' {
continue
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if isPrivateIP(ip) {
return ip, nil
}
}
}
return nil, errors.New("no IP")
}
func isPrivateIP(ip net.IP) bool {
var privateIPBlocks []*net.IPNet
for _, cidr := range []string{
// don't check loopback ips
//"127.0.0.0/8", // IPv4 loopback
//"::1/128", // IPv6 loopback
//"fe80::/10", // IPv6 link-local
"10.0.0.0/8", // RFC1918
"172.16.0.0/12", // RFC1918
"192.168.0.0/16", // RFC1918
} {
_, block, _ := net.ParseCIDR(cidr)
privateIPBlocks = append(privateIPBlocks, block)
}
for _, block := range privateIPBlocks {
if block.Contains(ip) {
return true
}
}
return false
}