C#获取计算机的MAC地址“离线”
Posted
技术标签:
【中文标题】C#获取计算机的MAC地址“离线”【英文标题】:C# Get Computer's MAC address "OFFLINE" 【发布时间】:2013-03-24 22:02:53 【问题描述】:在c#中没有互联网连接时,有什么方法可以获取计算机的mac地址? 当我有连接时我能够获得,但当我离线时无法获得。但我强烈需要我的工作的 mac 地址。
我的在线代码;
var macAddr =
(from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()).FirstOrDefault();
【问题讨论】:
你能去掉where nic.OperationalStatus == OperationalStatus.Up
这一行吗?
在线时,mac地址; 4CEB428D5072 离线时,mac地址为4CEB428D5073。为什么?
【参考方案1】:
来自 WMI:
public static string GetMACAddress1()
ManagementObjectSearcher objMOS = new ManagementObjectSearcher("Select * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMOS.Get();
string macAddress = String.Empty;
foreach (ManagementObject objMO in objMOC)
object tempMacAddrObj = objMO["MacAddress"];
if (tempMacAddrObj == null) //Skip objects without a MACAddress
continue;
if (macAddress == String.Empty) // only return MAC Address from first card that has a MAC Address
macAddress = tempMacAddrObj.ToString();
objMO.Dispose();
macAddress = macAddress.Replace(":", "");
return macAddress;
来自 System.Net 命名空间:
public static string GetMACAddress2()
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
if (sMacAddress == String.Empty)// only return MAC Address from first card
//IPInterfaceProperties properties = adapter.GetIPProperties(); Line is not required
sMacAddress = adapter.GetPhysicalAddress().ToString();
return sMacAddress;
对How to get the MAC address of system - C-Sharp Corner稍作修改
【讨论】:
需要IPInterfaceProperties properties = adapter.GetIPProperties();
这一行吗?
@Joel 不,这行不是必需的,基于我刚刚在我的开发箱上运行的测试。更新了答案以反映我的测试。【参考方案2】:
您可以在 C# (System.Management
) 中使用 WMI 来获取包含 MACAddress
属性的 Win32_NetworkAdapter
列表。
http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394216(v=vs.85).aspx
【讨论】:
以上是关于C#获取计算机的MAC地址“离线”的主要内容,如果未能解决你的问题,请参考以下文章
C# 获取本机CPU序列号,MAC地址,硬盘ID,本机IP地址,计算机名,物理内存,PC类型