net/interfaces: add List, GetList

And start moving funcs to methods on List.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
(cherry picked from commit 4a3e2842d9)
This commit is contained in:
Brad Fitzpatrick 2021-10-14 14:55:55 -07:00 committed by Maisem Ali
parent 9df2516f96
commit 5319c57590

View File

@ -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