-
Notifications
You must be signed in to change notification settings - Fork 115
/
interface_addresses_provider.go
47 lines (35 loc) · 1.11 KB
/
interface_addresses_provider.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
package ip
import (
"net"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
type InterfaceAddressesProvider interface {
Get() ([]InterfaceAddress, error)
}
type systemInterfaceAddrs struct{}
func NewSystemInterfaceAddressesProvider() InterfaceAddressesProvider {
return &systemInterfaceAddrs{}
}
func (s *systemInterfaceAddrs) Get() ([]InterfaceAddress, error) {
ifaces, err := net.Interfaces()
if err != nil {
return []InterfaceAddress{}, bosherr.WrapError(err, "Getting network interfaces")
}
interfaceAddrs := []InterfaceAddress{}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
return []InterfaceAddress{}, bosherr.WrapErrorf(err, "Getting addresses of interface '%s'", iface.Name)
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return []InterfaceAddress{}, bosherr.WrapErrorf(err, "Parsing addresses of interface '%s'", iface.Name)
}
if ipv4 := ip.To4(); ipv4 != nil {
interfaceAddrs = append(interfaceAddrs, NewSimpleInterfaceAddress(iface.Name, ipv4.String()))
}
}
}
return interfaceAddrs, nil
}