在 CentOS 机器上的 GoLang 中提取网络接口类型和名称

问题描述 投票:0回答:1

我有一个 CentOS 虚拟机,我可以在上面运行 Go 二进制文件。该机器运行 docker 容器等以及其他一些 Go 代码。我试图通过 Go 代码推断“以太网”类型的接口列表是什么。挑战在于,我在从 Go 库获取的对象中找不到任何类别。基本上,docker 容器也会创建 veth 端口,可以有环回端口等等。但我只对过滤以太网端口感兴趣(不是虚拟以太网端口,即必须过滤掉 veth 端口)。我也不想要 lo 或 docker0。挑战是我无法轻松地使用基于名称的字符串匹配并决定,因为端口名称可以是

eth
ens
或 Linux 机器上的任何此类名称。

我有示例代码和示例输出,但我正在尝试了解获取 eth 端口的正确方法。

package main

import (
    "fmt"
    "net"
    "os"
)

func availableInterfaces() {

    interfaces, err := net.Interfaces()

    if err != nil {
        fmt.Print(err)
        os.Exit(0)
    }

    fmt.Println("Available network interfaces on this machine : ")
    for _, i := range interfaces {
        //fmt.Printf("Name : %v \n", i.Name)
        fmt.Printf("Full object : %+v \n", i)
    }
}

func main() {
    availableInterfaces()
}
docker go centos
1个回答
0
投票

您可以使用“/sys/class/net/yourinterfacename/type”

然后将其与此处

指定的类型进行比较

例如:

package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
)

func isEthernet(in *net.Interface) bool {
    f, err := os.Open("/sys/class/net/" + in.Name + "/type")
    if err != nil {
        return false
    }
    scanner := bufio.NewScanner(f)

    scanner.Scan()

    return scanner.Text() == "1" // 1 is the type for ethernet
}

func main() {
    myinterface, _ := net.InterfaceByName("wlp1s0")
    fmt.Println(isEthernet(myinterface))
}

当我使用无线以太网接口时,这对我来说返回 true

© www.soinside.com 2019 - 2024. All rights reserved.