-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ip.go
87 lines (80 loc) · 1.84 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package extconfig
import (
"errors"
"fmt"
"net"
"go.uber.org/zap"
)
func mustParseCIDR(cidr string) *net.IPNet {
_, net, err := net.ParseCIDR(cidr)
if err != nil {
panic(err)
}
return net
}
var ulaPrefix = mustParseCIDR("fc00::/7")
func (e *ExtConfig) checkInterface(i net.Interface) ([]net.IP, error) {
ips := []net.IP{}
if i.Flags&net.FlagLoopback != 0 {
return ips, errors.New("interface is loopback")
}
if i.Flags&net.FlagUp == 0 {
return ips, errors.New("interface is down")
}
addrs, err := i.Addrs()
if err != nil {
return ips, err
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
continue
}
if ulaPrefix.Contains(ip) {
continue
}
ips = append(ips, ip)
}
return ips, nil
}
func (e *ExtConfig) GetInterfaceForIP(forIp net.IP) (*net.Interface, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range ifaces {
addrs, err := e.checkInterface(i)
if err != nil {
e.Logger().Debug("failed to get IPs from interface", zap.Error(err), zap.String("if", i.Name))
continue
}
for _, addr := range addrs {
if addr.Equal(forIp) {
return &i, nil
}
}
}
return nil, fmt.Errorf("faild to find interface for %s", forIp.String())
}
func (e *ExtConfig) GetIP() (net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range ifaces {
addrs, err := e.checkInterface(i)
if err != nil {
e.Logger().Debug("failed to get IPs from interface", zap.Error(err), zap.String("if", i.Name))
continue
}
if len(addrs) < 1 {
continue
}
e.Logger().Debug("Detected IP of instance", zap.String("ip", addrs[0].String()))
return addrs[0], nil
}
return nil, errors.New("failed to find IP, set `INSTANCE_IP`")
}