关于获得本机Mac Address的方法
网络上有讲获得Mac address的方法有如下:
1. 发送ARP命令,利用返回的Mac Address缓冲区得到
2. 用NetworkInterface.GetAllNetworkInterfaces()获得所有网卡(包括虚拟网卡),从而获得相应的Mac address
3. 还有是从本机的注册表中获得:
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
bool flag = false;
using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectCollection.GetEnumerator())
{
while (enumerator.MoveNext())
{
这三种方法第1,2种比较好,当本机有多块网卡,或虚拟网卡时,第三种在Win8下是不准确的。第1,2种都可以根据给定的参数IP值来准确定位对应的Mac Address.
第二种代码如下:
string macAddress = "" ;
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (!adapter.GetPhysicalAddress().ToString().Equals(""))
{
macAddress = adapter.GetPhysicalAddress().ToString();
for (int i = 1; i < 6; i++)
{
macAddress = macAddress.Insert(3 * i - 1, ":");
}
break;
}
}
第一种方法如下:
public static string GetMac(string p_Id)
{
IPAddress _Address;
if (!IPAddress.TryParse(p_Id, out _Address)) return "";
uint DestIP = System.BitConverter.ToUInt32(_Address.GetAddressBytes(), 0);
ulong pMacAddr = 0;
uint PhyAddrLen = 6;
uint error_code = SendARP(DestIP, 0, ref pMacAddr, ref PhyAddrLen);
byte[] _Bytes1 = BitConverter.GetBytes(pMacAddr);
return BitConverter.ToString(_Bytes1, 0, 6);
}
[DllImport("Iphlpapi.dll")]
public static extern uint SendARP(uint DestIP, uint SrcIP, ref ulong pMacAddr, ref uint PhyAddrLen);