C# 通过ARP发包获取路由器MAC地址
[DllImport("Iphlpapi.dll")]
private static unsafe extern int SendARP(Int32 dest, Int32 host, ref Int32 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
public static string GetMACFromIP()
{
string strRet = "unknown";
string A_strIP = "";
string hostName = Dns.GetHostName();
IPHostEntry iPHostEntry = Dns.GetHostEntry(hostName);
var addressV = iPHostEntry.AddressList.FirstOrDefault(q => q.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);//ip4地址
if (addressV != null)
{
A_strIP = addressV.ToString();
A_strIP = A_strIP.Substring(0, A_strIP.LastIndexOf(".")) + ".1";
Int32 intDest = inet_addr(A_strIP);
Int32[] arrMAC = new Int32[2];
Int32 intLen = 6;
int intResult = SendARP(intDest, 0, ref arrMAC[0], ref intLen);
if (intResult == 0)
{
Byte[] arrbyte = new Byte[8];
arrbyte[5] = (Byte)(arrMAC[1] >> 8);
arrbyte[4] = (Byte)arrMAC[1];
arrbyte[3] = (Byte)(arrMAC[0] >> 24);
arrbyte[2] = (Byte)(arrMAC[0] >> 16);
arrbyte[1] = (Byte)(arrMAC[0] >> 8);
arrbyte[0] = (Byte)arrMAC[0];
StringBuilder strbMAC = new StringBuilder();
for (int intIndex = 0; intIndex < 6; intIndex++)
{
if (intIndex > 0) strbMAC.Append("-");
strbMAC.Append(arrbyte[intIndex].ToString("X2"));
}
strRet = strbMAC.ToString();
}
}
return strRet;
}