C#通过ARP获取Mac与IP的对应表
2018-07-20 来源:open-open
原理:通过ARP命令查询,然后返回数据,根据返回数据进行分割保存
最后使用LINQ查询。
/// <summary> /// 获取ARP查询字符串 /// </summary> /// <returns></returns> private static string GetARPResult() { Process p = null; string output = string.Empty; try { p = Process.Start(new ProcessStartInfo("arp", "-a") { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true }); output = p.StandardOutput.ReadToEnd(); } catch (Exception ex) { throw new Exception("IPInfo: Error Retrieving 'arp -a' Results", ex); } finally { if (p != null) { p.Close(); } } return output; }
转换为对应的列表:
/// <summary> /// 获取IP地址与Mac地址对应数据表 /// </summary> /// <returns>Mac-IP</returns> public static List<string[]> GetIPInfo() { try { var list = new List<string[]>(); foreach (var arp in FLYFI_SHARE_CONNECTION.GetARPResult().Split(new char[] { '\n', '\r' })) { if (!string.IsNullOrEmpty(arp)) { var pieces = (from piece in arp.Split(new char[] { ' ', '\t' }) where !string.IsNullOrEmpty(piece) select piece).ToArray(); if (pieces.Length == 3) { //pieces[1]Mac //pieces[0]IP list.Add(new string[2] { pieces[1], pieces[0] }); } } } return list; } catch (Exception ex) { throw new Exception("IPInfo: Error Parsing 'arp -a' results", ex); } }
查询:
/// <summary> /// Mac地址转换为IP地址 /// </summary> /// <param name="str">IP</param> /// <returns></returns> public static string GetIpFromMac(string str) { str = str.Trim().ToString().Replace(":", "-"); var ipinfo = (from ip in FLYFI_SHARE_CONNECTION.GetIPInfo() where ip[0].ToLowerInvariant() == str.ToLowerInvariant() select ip[1]).FirstOrDefault(); return ipinfo; }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
下一篇:Java连接redis的使用示例
最新资讯
热门推荐