David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame^] | 1 | // Copyright 2013 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package utils |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "net" |
| 9 | |
| 10 | "github.com/juju/loggo" |
| 11 | ) |
| 12 | |
| 13 | var logger = loggo.GetLogger("juju.utils") |
| 14 | |
| 15 | // GetIPv4Address iterates through the addresses expecting the format from |
| 16 | // func (ifi *net.Interface) Addrs() ([]net.Addr, error) |
| 17 | func GetIPv4Address(addresses []net.Addr) (string, error) { |
| 18 | for _, addr := range addresses { |
| 19 | ip, _, err := net.ParseCIDR(addr.String()) |
| 20 | if err != nil { |
| 21 | return "", err |
| 22 | } |
| 23 | ipv4 := ip.To4() |
| 24 | if ipv4 == nil { |
| 25 | continue |
| 26 | } |
| 27 | return ipv4.String(), nil |
| 28 | } |
| 29 | return "", fmt.Errorf("no addresses match") |
| 30 | } |
| 31 | |
| 32 | // GetAddressForInterface looks for the network interface |
| 33 | // and returns the IPv4 address from the possible addresses. |
| 34 | func GetAddressForInterface(interfaceName string) (string, error) { |
| 35 | iface, err := net.InterfaceByName(interfaceName) |
| 36 | if err != nil { |
| 37 | logger.Errorf("cannot find network interface %q: %v", interfaceName, err) |
| 38 | return "", err |
| 39 | } |
| 40 | addrs, err := iface.Addrs() |
| 41 | if err != nil { |
| 42 | logger.Errorf("cannot get addresses for network interface %q: %v", interfaceName, err) |
| 43 | return "", err |
| 44 | } |
| 45 | return GetIPv4Address(addrs) |
| 46 | } |