第1种:
通过 ManagementObjectSearcher 类,进行查看系统相关信息
然后提取MAC地址.
/// <summary>
/// 获取本机的MAC;
/// </summary>
public string GetLocalMac()
{
string mac = null;
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (mo["IPEnabled"].ToString() == "True")
mac = mo["MacAddress"].ToString();
}
return (mac);
}
第2种:
通过NetworkInterface 接口获取接口信息,提取MAC地址
public string MacAdd()
{
try
{
string mac = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up) { mac += nic.GetPhysicalAddress().ToString().Trim(); break; }
}
if (!Model.Helper.CheckNull(mac)) { if (mac.Length < 3) { mac = null; } }
return mac;
}
catch (Exception) { return null; }
}
第3种:
获取同一个IP下的MAC地址信息
//只能获取同网段的远程主机MAC地址. 因为在标准网络协议下,ARP包是不能跨网段传输的,故想通过ARP协议是无法查询跨网段设备MAC地址的。
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
/// <summary>
/// 获取ip对应的MAC地址
/// </summary>
public string GetMacAddress(string ip)
{
Int32 ldest = inet_addr(ip); //目的ip
Int32 lhost = inet_addr("127.0.0.1"); //本地ip
try
{
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len); //使用系统API接口发送ARP请求,解析ip对应的Mac地址
return Convert.ToString(macinfo, 16);
}
catch (Exception err)
{
Console.WriteLine("Error:{0}", err.Message);
}
return "获取Mac地址失败";
}
运行结果: