cmd/cli: extend list of valid interfaces for MacOS

By parsing "networksetup -listallhardwareports" output to get list of
available hardware ports.
This commit is contained in:
Cuong Manh Le
2024-08-01 15:57:45 +07:00
committed by Cuong Manh Le
parent 82e0d4b0c4
commit 5f4a399850
5 changed files with 81 additions and 21 deletions
+28 -18
View File
@@ -43,22 +43,32 @@ func networkServiceName(ifaceName string, r io.Reader) string {
return ""
}
// validInterface reports whether the *net.Interface is a valid one, which includes en0 -> en10.
// - en0: physical wireless
// - en1: Thunderbolt 1
// - en2: Thunderbolt 2
// - en3: Thunderbolt 3
// - en4: Thunderbolt 4
// - ...
// - en10: iPad
//
// For full list, see: https://unix.stackexchange.com/questions/603506/what-are-these-ifconfig-interfaces-on-macos
func validInterface(iface *net.Interface) bool {
switch iface.Name {
case "en0", "en1", "en2", "en3", "en4", "en5",
"en6", "en7", "en8", "en9", "en10":
return true
default:
return false
}
// validInterface reports whether the *net.Interface is a valid one.
func validInterface(iface *net.Interface, validIfacesMap map[string]struct{}) bool {
_, ok := validIfacesMap[iface.Name]
return ok
}
func validInterfacesMap() map[string]struct{} {
b, err := exec.Command("networksetup", "-listallhardwareports").Output()
if err != nil {
return nil
}
return parseListAllHardwarePorts(bytes.NewReader(b))
}
// parseListAllHardwarePorts parses output of "networksetup -listallhardwareports"
// and returns map presents all hardware ports.
func parseListAllHardwarePorts(r io.Reader) map[string]struct{} {
m := make(map[string]struct{})
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
after, ok := strings.CutPrefix(line, "Device: ")
if !ok {
continue
}
m[after] = struct{}{}
}
return m
}