本文使用二种方式来获取mac address.
1.
只能获取本机的.
using System.Management;
ManagementClass
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc2 = mc.GetInstances();
foreach (ManagementObject mo in moc2)
{
if ((bool)mo["IPEnabled"] == true)
this.textBox1.Text = mo["MacAddress"].ToString();
mo.Dispose();
}
2. 此种方法可以获取远程MAC地址
using System.Runtime.InteropServices;
[DllImport("Iphlpapi.dll")]
static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
[DllImport("Ws2_32.dll")]
static extern Int32 inet_addr(string ipaddr);
///<summary>
/// SendArp
获取MAC地址
///</summary>
///<param name="RemoteIP">
目标机器的IP地址如(192.168.1.1)
</param>
///<returns>
目标机器的mac 地址
</returns>
public static string GetMacAddress(string RemoteIP)
{
StringBuilder macAddress = new StringBuilder();
try
{
Int32 remote = inet_addr(RemoteIP);
Int64 macInfo = new Int64();
Int32 length = 6;
SendARP(remote, 0, ref macInfo, ref length);
string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
int x = 12;
for (int i = 0; i < 6; i++)
{
if (i == 5)
{
macAddress.Append(temp.Substring(x - 2, 2));
}
else
{
macAddress.Append(temp.Substring(x - 2, 2) + "-");
}
x -= 2;
}
return macAddress.ToString();
}
catch
{
return macAddress.ToString();
}
}