Go语言获取Ubuntu所有网卡名

Go语言获取Ubuntu所有网卡名

需求

  • 获取当前机器下所有网卡名,以字符串数组的形式返回

实现demo

package main

import (
	"fmt"
	"os/exec"
	"strings"
)

func main() {
	s := GetLocalNetDeviceNames()
	fmt.Println(s)
}

func GetLocalNetDeviceNames() []string {
	baseNicPath := "/sys/class/net/"
	cmd := exec.Command("ls", baseNicPath)
	buf, _ := cmd.Output()
	output := string(buf)
	str := ""
	for _, device := range strings.Split(output, "
") {
		if len(device) > 1 {
			if device != "lo" {
				str += device+"|"
			}
		}
	}
	return strings.Split(str[:len(str)-1],"|")
}

输出

mv@mv-Super-Server:~$ ./test
[eno1 eno2]
原文地址:https://www.cnblogs.com/Kingram/p/13453352.html