在 Golang 中,可以使用 net 包中的 Interfaces() 函数获取所有网络接口信息,然后遍历每个接口,使用 Addrs() 函数获取该接口的所有 IP 地址信息。如果接口的硬件地址(MAC 地址)与指定的 MAC 地址匹配,则可以将该接口的 IP 地址作为查询结果返回。

以下是一个示例代码:

package main

import (
    "fmt"
    "net"
)

func main() {
    // 指定要查询的 MAC 地址
    mac := net.HardwareAddr{0x00, 0x11, 0x22, 0x33, 0x44, 0x55}

    // 获取所有网络接口信息
    ifaces, err := net.Interfaces()
    if err != nil {
        fmt.Println("Failed to get network interfaces:", err)
        return
    }

    // 遍历每个接口
    for _, iface := range ifaces {
        // 获取该接口的硬件地址(MAC 地址)
        ifaceMAC := iface.HardwareAddr
        if ifaceMAC == nil {
            continue
        }

        // 如果 MAC 地址匹配,则获取该接口的所有 IP 地址
        if ifaceMAC.Equal(mac) {
            addrs, err := iface.Addrs()
            if err != nil {
                fmt.Println("Failed to get IP addresses for interface", iface.Name, ":", err)
                continue
            }

            // 遍历该接口的所有 IP 地址,输出 IPv4 地址
            for _, addr := range addrs {
                ipnet, ok := addr.(*net.IPNet)
                if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
                    fmt.Println("Found IP address", ipnet.IP.String(), "for MAC address", ifaceMAC.String())
                }
            }
        }
    }
}

在上面的示例代码中,我们指定了要查询的 MAC 地址为 00:11:22:33:44:55,然后遍历所有网络接口,如果接口的 MAC 地址与指定的 MAC 地址匹配,则输出该接口的所有 IPv4 地址。注意,该代码只能查询本机上的网络接口信息,无法查询其他设备的网络接口信息。

Golang: 通过 MAC 地址查询 IP 地址

原文地址: https://www.cveoy.top/t/topic/fXD6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录