summaryrefslogtreecommitdiffhomepage
path: root/dhcpv6/iputils.go
diff options
context:
space:
mode:
authorMikoĊ‚aj Walczak <mikiwalczak+github@gmail.com>2018-08-31 17:39:44 +0100
committerinsomniac <insomniacslk@users.noreply.github.com>2018-08-31 17:39:44 +0100
commit1555d8ae9642629d8ef214d895d8bccadd247f2f (patch)
treee31ba526cfab75fa7b2e31e63bcc10ebea3f8faa /dhcpv6/iputils.go
parent59404e9a78222a80a9e4c4af52eae4c9276f7681 (diff)
GetGlobalAddr utility function (#81)
Diffstat (limited to 'dhcpv6/iputils.go')
-rw-r--r--dhcpv6/iputils.go48
1 files changed, 31 insertions, 17 deletions
diff --git a/dhcpv6/iputils.go b/dhcpv6/iputils.go
index c3ac3aa..2b9788c 100644
--- a/dhcpv6/iputils.go
+++ b/dhcpv6/iputils.go
@@ -5,26 +5,40 @@ import (
"net"
)
-func GetLinkLocalAddr(ifname string) (*net.IP, error) {
- ifaces, err := net.Interfaces()
+// InterfaceAddresses is used to fetch addresses of an interface with given name
+var InterfaceAddresses func(string) ([]net.Addr, error) = interfaceAddresses
+
+func interfaceAddresses(ifname string) ([]net.Addr, error) {
+ iface, err := net.InterfaceByName(ifname)
if err != nil {
return nil, err
}
- for _, iface := range ifaces {
- if iface.Name != ifname {
- continue
- }
- ifaddrs, err := iface.Addrs()
- if err != nil {
- return nil, err
- }
- for _, ifaddr := range ifaddrs {
- if ifaddr, ok := ifaddr.(*net.IPNet); ok {
- if ifaddr.IP.To4() == nil && ifaddr.IP.IsLinkLocalUnicast() {
- return &ifaddr.IP, nil
- }
- }
+ return iface.Addrs()
+}
+
+func getMatchingAddr(ifname string, matches func(net.IP) bool) (net.IP, error) {
+ ifaddrs, err := InterfaceAddresses(ifname)
+ if err != nil {
+ return nil, err
+ }
+ for _, ifaddr := range ifaddrs {
+ if ifaddr, ok := ifaddr.(*net.IPNet); ok && matches(ifaddr.IP) {
+ return ifaddr.IP, nil
}
}
- return nil, fmt.Errorf("No link-local address found for interface %v", ifname)
+ return nil, fmt.Errorf("no matching address found for interface %s", ifname)
+}
+
+// GetLinkLocalAddr returns a link-local address for the interface
+func GetLinkLocalAddr(ifname string) (net.IP, error) {
+ return getMatchingAddr(ifname, func(ip net.IP) bool {
+ return ip.To4() == nil && ip.IsLinkLocalUnicast()
+ })
+}
+
+// GetGlobalAddr returns a global address for the interface
+func GetGlobalAddr(ifname string) (net.IP, error) {
+ return getMatchingAddr(ifname, func(ip net.IP) bool {
+ return ip.To4() == nil && ip.IsGlobalUnicast()
+ })
}