C# 擷取MAC地址
方法一: 使用 ManagementClass
string strMAC = "";
ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection MOC = MC.GetInstances();
foreach (ManagementObject moc in MOC)
{
if (moc["IPEnabled"].ToString() == "True")
{
strMAC = moc["MacAddress"].ToString();
}
}
方法二:使用NetworkInterface
string strMAC="";
NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in fNetworkInterfaces)
{
strMAC = adapter.GetPhysicalAddress().ToString();
}
如果你的電腦中既有無線網卡,也有有線網卡,而且在你使用寬頻時候還會有一個虛擬MAC地址,這時要想擷取本地的有線網卡地址,就要實現MAC地址的區分,結合CMD下ipconfig /all
命令的內容
Ethernet adapter 本地串連:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Realtek PCIe GBE Family Controller
Physical Address. . . . . . . . . : 00-26-9E-8B-A9-F2
Dhcp Enabled. . . . . . . . . . . : No
IP Address. . . . . . . . . . . . : 192.168.9.123
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.9.1
Ethernet adapter 無線網路串連:
MediaState . . . . . . . . . . . : Media disconnected
Description . . . . . . . . . . . : 11b/g/n Wireless LAN Mini-PCI Express Adapter II
Physical Address. . . . . . . . . : 70-1A-04-51-4D-5E
PPP adapter 寬頻連線:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : WAN (PPP/SLIP) Interface
Physical Address. . . . . . . . . : 00-53-45-00-00-00
Dhcp Enabled. . . . . . . . . . . : No
IP Address. . . . . . . . . . . . : 117.93.142.100
Subnet Mask . . . . . . . . . . . : 255.255.255.255
Default Gateway . . . . . . . . . : 117.93.142.100
DNS Servers . . . . . . . . . . . : 61.177.7.1
221.228.255.1
NetBIOS over Tcpip. . . . . . . . : Disabled
發現可以在串連的Description中區分MAC
區分條件
if(adapter.Description.Contains("PCI") && !adapter.Description.Contains("Wireless"))
// NetworkInterface
// 這個條件可以判斷出有線網卡的MAC
if (strDescription.Contains("PCI")&&!strDescription.Contains("Wireless"))
// ManagementClass
// 這個條件可以判斷出有線網卡的MAC
也可以比較3個串連名稱(本地串連,無線網路串連,寬頻連線),但是並不是每台機上的串連名稱都是這個,所以用這個作為條件不可靠!
我看網上有人讀註冊表來區分,他們是通過讀取註冊表網卡資訊中的某個索引值是否含有"PCI"來區分無線網卡和有線網卡,這裡我想說的是,無線網卡也有PCI的。
Ethernet adapter 無線網路串連:
MediaState . . . . . . . . . . . : Media disconnected
Description . . . . . . . . . . . : 11b/g/n Wireless LAN Mini-PCI Express Adapter II
Physical Address. . . . . . . . . : 70-1A-04-51-4D-5E