c# - 使用“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 作为字符串存储在某处?
解决方案
我假设您以某种方式(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 地址。在不了解您的具体用例的情况下,很难说这种权衡是否适用于您,我只是指出这是一种选择。
推荐阅读
- node.js - ffmpeg --help, node child_process spawn trigger stderr
- python - 计算只包含一次给定单词的固定长度字符串的数量
- visual-studio-code - 使用 cl.exe 构建未完成运行
- spring-boot - IO 错误:仅当数据库使用 IN 语句运行 JDBCTemplate 查询时,套接字读取才会超时
- reactjs - Webpack 无法转换 CRA 应用程序,尝试从 URL 导入 firebase
- azure - Log Analytics 数据导出到存储帐户 - 所有表
- android - 在可点击修饰符中获取上下文的最佳方法
- android - 当 OnclikcListener i=used 时,活动没有启动
- sql - 关于左连接的 HIVE sql 调试
- vue.js - 为什么 vue js 中的 DataForm() 为空?