forked from juju/utils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
network.go
46 lines (40 loc) · 1.16 KB
/
network.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
// Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package utils
import (
"fmt"
"net"
"github.com/juju/loggo"
)
var logger = loggo.GetLogger("juju.utils")
// GetIPv4Address iterates through the addresses expecting the format from
// func (ifi *net.Interface) Addrs() ([]net.Addr, error)
func GetIPv4Address(addresses []net.Addr) (string, error) {
for _, addr := range addresses {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return "", err
}
ipv4 := ip.To4()
if ipv4 == nil {
continue
}
return ipv4.String(), nil
}
return "", fmt.Errorf("no addresses match")
}
// GetAddressForInterface looks for the network interface
// and returns the IPv4 address from the possible addresses.
func GetAddressForInterface(interfaceName string) (string, error) {
iface, err := net.InterfaceByName(interfaceName)
if err != nil {
logger.Errorf("cannot find network interface %q: %v", interfaceName, err)
return "", err
}
addrs, err := iface.Addrs()
if err != nil {
logger.Errorf("cannot get addresses for network interface %q: %v", interfaceName, err)
return "", err
}
return GetIPv4Address(addrs)
}