Repository navigation
Expand file tree
/
Copy pathnetwork.go
More file actions
83 lines (75 loc) · 2.32 KB
/
Copy pathnetwork.go
File metadata and controls
83 lines (75 loc) · 2.32 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package utils
import (
"fmt"
"net"
"github.com/juju/loggo/v2"
)
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")
}
// GetIPv6Address iterates through the addresses expecting the format from
// func (ifi *net.Interface) Addrs() ([]net.Addr, error) and returns the first
// non-link local address.
func GetIPv6Address(addresses []net.Addr) (string, error) {
_, llNet, _ := net.ParseCIDR("fe80::/10")
for _, addr := range addresses {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return "", err
}
if ip.To4() == nil && !llNet.Contains(ip) {
return ip.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)
}
// GetV4OrV6AddressForInterface looks for the network interface
// and returns preferably the IPv4 address, and if it doesn't
// exists then IPv6 address.
func GetV4OrV6AddressForInterface(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
}
if ip, err := GetIPv4Address(addrs); err == nil {
return ip, nil
}
return GetIPv6Address(addrs)
}