C#獲取MAC地址
/// <summary> /// 獲取MAC地址(返回第一個物理以太網卡的mac地址) /// </summary> /// <returns>成功返回mac地址,失敗返回null</returns> public string getMacAddress() { string macAddress = null; try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet")) //是以太網卡 { string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection"; RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false); if (rk != null) { // 區分 PnpInstanceID // 如果前面有 PCI 就是本機的真實網卡 // MediaSubType 為 01 則是常見網卡,02為無線網卡。 string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString(); int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0)); if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI") //是物理網卡 { macAddress = adapter.GetPhysicalAddress().ToString(); break; } else if (fMediaSubType == 1) //虛擬網卡 continue; else if (fMediaSubType == 2) //無線網卡(上面判斷Ethernet時已經排除了) continue; } } } } catch { macAddress = null; } return macAddress; }
