From 5319c575901f8e5991e4d500b9e1212d59357947 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Thu, 14 Oct 2021 14:55:55 -0700 Subject: [PATCH] net/interfaces: add List, GetList And start moving funcs to methods on List. Signed-off-by: Brad Fitzpatrick (cherry picked from commit 4a3e2842d9ed10a3818e594835fa0d33ffcfee83) --- net/interfaces/interfaces.go | 38 +++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/net/interfaces/interfaces.go b/net/interfaces/interfaces.go index 037bef7f3..c8323318b 100644 --- a/net/interfaces/interfaces.go +++ b/net/interfaces/interfaces.go @@ -183,14 +183,20 @@ func (i Interface) Addrs() ([]net.Addr, error) { return i.Interface.Addrs() } -// ForeachInterfaceAddress calls fn for each interface's address on -// the machine. The IPPrefix's IP is the IP address assigned to the -// interface, and Bits are the subnet mask. +// ForeachInterfaceAddress is a wrapper for GetList, then +// List.ForeachInterfaceAddress. func ForeachInterfaceAddress(fn func(Interface, netaddr.IPPrefix)) error { - ifaces, err := netInterfaces() + ifaces, err := GetList() if err != nil { return err } + return ifaces.ForeachInterfaceAddress(fn) +} + +// ForeachInterfaceAddress calls fn for each interface in ifaces, with +// all its addresses. The IPPrefix's IP is the IP address assigned to +// the interface, and Bits are the subnet mask. +func (ifaces List) ForeachInterfaceAddress(fn func(Interface, netaddr.IPPrefix)) error { for _, iface := range ifaces { addrs, err := iface.Addrs() if err != nil { @@ -208,11 +214,21 @@ func ForeachInterfaceAddress(fn func(Interface, netaddr.IPPrefix)) error { return nil } -// ForeachInterface calls fn for each interface on the machine, with +// ForeachInterface is a wrapper for GetList, then +// List.ForeachInterface. +func ForeachInterface(fn func(Interface, []netaddr.IPPrefix)) error { + ifaces, err := GetList() + if err != nil { + return err + } + return ifaces.ForeachInterface(fn) +} + +// ForeachInterface calls fn for each interface in ifaces, with // all its addresses. The IPPrefix's IP is the IP address assigned to // the interface, and Bits are the subnet mask. -func ForeachInterface(fn func(Interface, []netaddr.IPPrefix)) error { - ifaces, err := netInterfaces() +func (ifaces List) ForeachInterface(fn func(Interface, []netaddr.IPPrefix)) error { + ifaces, err := GetList() if err != nil { return err } @@ -589,6 +605,14 @@ func RegisterInterfaceGetter(getInterfaces func() ([]Interface, error)) { altNetInterfaces = getInterfaces } +// List is a list of interfaces on the machine. +type List []Interface + +// GetList returns the list of interfaces on the machine. +func GetList() (List, error) { + return netInterfaces() +} + // netInterfaces is a wrapper around the standard library's net.Interfaces // that returns a []*Interface instead of a []net.Interface. // It exists because Android SDK 30 no longer permits Go's net.Interfaces