using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Tech_Demo { public class ArpUtil { /// /// 引入windowsAPI /// //用于转换ip地址 [DllImport("ws2_32.dll")] public static extern int inet_addr(string cp); //用于发送APR包(根据APR协议!) [DllImport("IPHLPAPI.dll")] public static extern int SendARP(int DestIP, int ScrIP, ref long pMacAddr, ref int PhyAddrLen); /// /// 根据ARP映射获取指定IP的MAC地址 /// /// /// public string GetMACAddressByIP(string ip) { StringBuilder macRouteBuilder = new StringBuilder(); string macRoute; try { int ldest = inet_addr(ip); //将IP地址从 点数格式转换成无符号长整型 long macinfo = new long(); int len = 6; //SendARP函数发送一个地址解析协议(ARP)请求获得指定的目的地IPv4地址相对应的物理地址 SendARP(ldest, 0, ref macinfo, ref len); string TmpMac = Convert.ToString(macinfo, 16).PadLeft(12, '0'); //转换成16进制 // for (int i = 10; i >= 0; i = i - 2) //反过来读取,原因可以查看接口函数sendApr! { macRouteBuilder.Append(TmpMac.Substring(i, 2).ToUpper()); if (i >= 2) { macRouteBuilder.Append("-"); } } } catch (Exception Mye) { macRouteBuilder.Append("获取远程主机的MAC错误:"); macRouteBuilder.Append(Mye.ToString()); } macRoute = macRouteBuilder.ToString(); return macRoute; } /// /// 获取ARP查询字符串 /// /// private static string GetArpResult() { Process p = null; string output = string.Empty; try { p = Process.Start(new ProcessStartInfo("arp", "-a -n 192.168.0.105") { 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; } /// /// 获取IP地址与Mac地址对应数据表 /// /// Mac-IP public static List GetIpInfo() { try { var list = new List(); var arpResult = GetArpResult(); foreach (var arp in arpResult.Split(new char[] { '\n', '\r' })) { if (!string.IsNullOrEmpty(arp)) { var oArp = arp.Split(new char[] { ' ', '\t' }); var pieces = (from piece in oArp 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); } } } }