首页 > 解决方案 > 使用“arp -a”获取对应IP地址的MAC地址

问题描述

我试图将手机的 MAC 地址转换为它的 IP 地址。

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

使用上面的代码,我将其存储在以下形式的列表中:

  192.168.137.1         2e-bb-58-0a-2f-34     dynamic
  192.168.137.44        a8-3e-0e-61-3f-db     dynamic
  192.168.137.91        d4-63-c6-b2-ac-38     dynamic
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.252           01-00-5e-00-00-fc     static

我想不通的是,如何检索给定 MAC 的特定 IP。假设我的手机是物理地址的设备:a8-3e-0e-61-3f-db,我怎样才能将它的 IP 作为字符串存储在某处?

标签: c#stringlistip-addressmac-address

解决方案


我假设您以某种方式(ExecuteCommandLine方法)获得了字符串列表,并希望能够根据 arp 值对其进行过滤。正则表达式可以是一个选项:

void Main()
{
    // just setting it up for testing
    List<string> result = new List<string>();
    result.Add("192.168.137.1         2e-bb-58-0a-2f-34     dynamic");
    result.Add("192.168.137.44        a8-3e-0e-61-3f-db     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("192.168.137.91        d4-63-c6-b2-ac-38     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.252           01-00-5e-00-00-fc     static");

    // this is the part you want
    ConcurrentDictionary<string,string> arps = new ConcurrentDictionary<string, string>();
    foreach (var s in result)
    {
        var matches = Regex.Match(s, @"((?:\d+\.?){4})\s+((?:[0-9a-f]{2}-?){6}).*");        
        arps.TryAdd(matches.Groups[2].Value, matches.Groups[1].Value);
    }

    Console.WriteLine(arps["01-00-5e-00-00-16"]);
}

注意:在这里选择字典有好处也有坏处。您将获得O(1)元素访问时间,但那里不能有重复的 MAC 地址。在不了解您的具体用例的情况下,很难说这种权衡是否适用于您,我只是指出这是一种选择。


推荐阅读