美文网首页技术初心程序园
GO 语言取得 Ethernet 类型的网卡地址

GO 语言取得 Ethernet 类型的网卡地址

作者: triplestudio | 来源:发表于2019-11-01 22:49 被阅读0次

    在 C# 中取得 Ethernet 类型的网卡地址

    在 C# 中,因为有 NetworkInterface .NetworkInterfaceType == NetworkInterfaceType.Ethernet 所以,很容易在代码中进行判断。

    public static PhysicalAddress GetMacAddress()
    {
        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            // Only consider Ethernet network interfaces
            if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) //  nic.OperationalStatus == OperationalStatus.Up
            {
                return nic.GetPhysicalAddress();
            }
        }
        return null;
    }
    

    在 GO 中的处理办法

    搜索百度百十回,没有找到答案,无奈,搜索 net 包的源码,找到蛛丝马迹,在未公开的方法中,找到一个类型的判断语句。net/interface_windows.go 中,有 case windows.IF_TYPE_ETHERNET_CSMACD 的类型判断。再查找 IF_TYPE_ETHERNET_CSMACD 的资料,正是这里所需要的。
    参考:IP_INTERFACE_NAME_INFO_W2KSP1 structure

    image.png

    于是,将需要的部分复制出来加以改造,得到 IsEthernet 方法,结合 net 包中已有的方法,参数使用 net.Interface 的 Index 来使用。完整代码如下:

    package machine
    
    import (
        "errors"
        "net"
        "os"
        "strings"
        "syscall"
        "unsafe"
    
        "golang.org/x/sys/windows"
    )
    
    func GetMACAddress() (string, error) {
        netInterfaces, err := net.Interfaces()
        if err != nil {
            panic(err.Error())
        }
    
        mac, macerr := "", errors.New("no valid mac address")
        for i := 0; i < len(netInterfaces); i++ {
            if (netInterfaces[i].Flags&net.FlagLoopback) == 0 && strings.Contains(netInterfaces[i].Flags.String(), "broadcast") {
                index := netInterfaces[i].Index
    
                if isEthernet(index) {
                    mac = netInterfaces[i].HardwareAddr.String()
                    return mac, nil
                }
            }
        }
        return mac, macerr
    }
    
    // 根据网卡接口 Index 判断其是否为 Ethernet 网卡
    func isEthernet(ifindex int) bool {
        aas, err := adapterAddresses()
        if err != nil {
            return false
        }
        result := false
        for _, aa := range aas {
            index := aa.IfIndex
            if ifindex == int(index) {
                switch aa.IfType {
                case windows.IF_TYPE_ETHERNET_CSMACD:
                    result = true
                }
    
                if result {
                    break
                }
            }
        }
        return result
    }
    
    // 从 net/interface_windows.go 中复制过来
    func adapterAddresses() ([]*windows.IpAdapterAddresses, error) {
        var b []byte
        l := uint32(15000) // recommended initial size
        for {
            b = make([]byte, l)
            err := windows.GetAdaptersAddresses(syscall.AF_UNSPEC, windows.GAA_FLAG_INCLUDE_PREFIX, 0, (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])), &l)
            if err == nil {
                if l == 0 {
                    return nil, nil
                }
                break
            }
            if err.(syscall.Errno) != syscall.ERROR_BUFFER_OVERFLOW {
                return nil, os.NewSyscallError("getadaptersaddresses", err)
            }
            if l <= uint32(len(b)) {
                return nil, os.NewSyscallError("getadaptersaddresses", err)
            }
        }
        var aas []*windows.IpAdapterAddresses
        for aa := (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])); aa != nil; aa = aa.Next {
            aas = append(aas, aa)
        }
        return aas, nil
    }
    
    

    相关文章

      网友评论

        本文标题:GO 语言取得 Ethernet 类型的网卡地址

        本文链接:https://www.haomeiwen.com/subject/reiqbctx.html