美文网首页
go获取机器的mac地址和ip

go获取机器的mac地址和ip

作者: 大地缸 | 来源:发表于2021-01-22 22:04 被阅读0次

    title: "Go获取机器的mac地址和ip"
    date: 2021-01-22T21:23:22+08:00
    draft: true
    tags: ['go']
    author: "dadigang"
    author_cn: "大地缸"
    personal: "http://www.real007.cn"


    关于作者

    http://www.real007.cn/about

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func getMacAddrs() (macAddrs []string) {
        netInterfaces, err := net.Interfaces()
        if err != nil {
            fmt.Printf("fail to get net interfaces: %v", err)
            return macAddrs
        }
    
        for _, netInterface := range netInterfaces {
            macAddr := netInterface.HardwareAddr.String()
            if len(macAddr) == 0 {
                continue
            }
    
            macAddrs = append(macAddrs, macAddr)
        }
        return macAddrs
    }
    
    func getIPs() (ips []string) {
    
        interfaceAddr, err := net.InterfaceAddrs()
        if err != nil {
            fmt.Printf("fail to get net interface addrs: %v", err)
            return ips
        }
    
        for _, address := range interfaceAddr {
            ipNet, isValidIpNet := address.(*net.IPNet)
            if isValidIpNet && !ipNet.IP.IsLoopback() {
                if ipNet.IP.To4() != nil {
                    ips = append(ips, ipNet.IP.String())
                }
            }
        }
        return ips
    }
    
    func main() {
        fmt.Printf("mac addrs: %q\n", getMacAddrs())
        fmt.Printf("ips: %q\n", getIPs())
    }
    

    相关文章

      网友评论

          本文标题:go获取机器的mac地址和ip

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