Exemple #1
0
// getAddressForInterfaceImpl looks for the network interface
// and returns the IPv4 address from the possible addresses.
func getAddressForInterfaceImpl(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 utils.GetIPv4Address(addrs)
}
Exemple #2
0
func (*networkSuite) TestGetIPv4Address(c *gc.C) {
	for _, test := range []struct {
		addresses   []net.Addr
		expected    string
		errorString string
	}{{
		addresses: makeAddresses(
			"complete",
			"nonsense"),
		errorString: "invalid CIDR address: complete",
	}, {
		addresses: makeAddresses(
			"fe80::90cf:9dff:fe6e:ece/64",
		),
		errorString: "no addresses match",
	}, {
		addresses: makeAddresses(
			"fe80::90cf:9dff:fe6e:ece/64",
			"10.0.3.1/24",
		),
		expected: "10.0.3.1",
	}, {
		addresses: makeAddresses(
			"10.0.3.1/24",
			"fe80::90cf:9dff:fe6e:ece/64",
		),
		expected: "10.0.3.1",
	}} {
		ip, err := utils.GetIPv4Address(test.addresses)
		if test.errorString == "" {
			c.Assert(err, gc.IsNil)
			c.Assert(ip, gc.Equals, test.expected)
		} else {
			c.Assert(err, gc.ErrorMatches, test.errorString)
			c.Assert(ip, gc.Equals, "")
		}
	}
}