-
Notifications
You must be signed in to change notification settings - Fork 51
/
netinterfaces.go
67 lines (54 loc) · 1.32 KB
/
netinterfaces.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 netinterfaces
import (
"fmt"
"net"
"go.uber.org/zap"
)
// NetworkInterface holds info of a network interface
type NetworkInterface struct {
Name string
IPs []net.IP
IPNets []*net.IPNet
Flags net.Flags
}
// GetInterfacesInfo returns interface info
func GetInterfacesInfo() ([]NetworkInterface, error) {
netInterfaces := []NetworkInterface{}
// List interfaces
ifaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("unable to get interfaces: %v", err)
}
for _, intf := range ifaces {
ipList := []net.IP{}
ipNetList := []*net.IPNet{}
// List interface addresses
addrs, err := intf.Addrs()
if err != nil {
zap.L().Warn("unable to get interface addresses",
zap.String("interface", intf.Name),
zap.Error(err))
continue
}
for _, addr := range addrs {
ip, ipNet, err := net.ParseCIDR(addr.String())
if err != nil {
zap.L().Warn("unable to parse address",
zap.String("interface", intf.Name),
zap.String("addr", addr.String()),
zap.Error(err))
continue
}
ipList = append(ipList, ip)
ipNetList = append(ipNetList, ipNet)
}
netInterface := NetworkInterface{
Name: intf.Name,
IPs: ipList,
IPNets: ipNetList,
Flags: intf.Flags,
}
netInterfaces = append(netInterfaces, netInterface)
}
return netInterfaces, nil
}