1

有没有办法获取与特定 MAC 地址对应的 IP(或主机名)?

到目前为止,我发现是从 IP 获取主机名,反之亦然,使用System.Net.Dns.

4

2 回答 2

4

你可以使用这个类

public class IPMacMapper
{
    private static List<IPAndMac> list;

    private static StreamReader ExecuteCommandLine(String file, String arguments = "")
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.FileName = file;
        startInfo.Arguments = arguments;

        Process process = Process.Start(startInfo);

        return process.StandardOutput;
    }

    private static void InitializeGetIPsAndMac()
    {
        if (list != null)
            return;

        var arpStream = ExecuteCommandLine("arp", "-a");
        List<string> result = new List<string>();
        while (!arpStream.EndOfStream)
        {
            var line = arpStream.ReadLine().Trim();
            result.Add(line);
        }

        list = result.Where(x => !string.IsNullOrEmpty(x) && (x.Contains("dynamic") || x.Contains("static")))
            .Select(x =>
            {
                string[] parts = x.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                return new IPAndMac { IP = parts[0].Trim(), MAC = parts[1].Trim() };
            }).ToList();
    }

    public static string FindIPFromMacAddress(string macAddress)
    {
        InitializeGetIPsAndMac();
        IPAndMac item = list.SingleOrDefault(x => x.MAC == macAddress);
        if (item == null)
            return null;
        return item.IP;
    }

    public static string FindMacFromIPAddress(string ip)
    {
        InitializeGetIPsAndMac();
        IPAndMac item = list.SingleOrDefault(x => x.IP == ip);
        if (item == null)
            return null;
        return item.MAC;
    }

    private class IPAndMac
    {
        public string IP { get; set; }
        public string MAC { get; set; }
    }
}

并将其用作

string ipAddress = IPMacMapper.FindIPFromMacAddress("some-mac-address");
string macAddress = IPMacMapper.FindMacFromIPAddress("some-ip-address");
于 2017-10-13T14:18:28.070 回答
0

您正在寻找的是阅读计算机的ARP列表。
然后解析它以找到请求的 MAC 地址...请注意,arp -a它同时具有 IP 和 MAC,因此您只需要匹配请求的地址即可。

这是如何在 C# 中完成的示例

于 2013-03-12T10:12:30.040 回答