2013-04-03 38 views
9

Có cách nào để nhận địa chỉ mac của máy tính khi không có kết nối internet trong C#? Tôi có thể nhận được khi tôi có kết nối nhưng không thể nhận được khi tôi ngoại tuyến. Nhưng mạnh mẽ tôi cần địa chỉ mac cho công việc của tôi.C# Nhận địa chỉ MAC của máy tính "OFFLINE"

Mã trực tuyến của tôi;

var macAddr = 
     (from nic in NetworkInterface.GetAllNetworkInterfaces() 
     where nic.OperationalStatus == OperationalStatus.Up 
     select nic.GetPhysicalAddress().ToString()).FirstOrDefault(); 
+0

có thể bạn chỉ cần loại bỏ các 'nơi nic.OperationalStatus = = Dòng OperationalStatus.Up'? – Pondidum

+0

Khi trực tuyến, địa chỉ mac; 4CEB428D5072 Khi ngoại tuyến, địa chỉ mac 4CEB428D5073. Tại sao? –

Trả lời

24

Từ 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; 
} 

Từ System.Net namespace:

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; 
} 

Hơi sửa đổi từ How to get the MAC address of system - C-Sharp Corner

+0

Thuộc tính 'IPInterfaceProperties properties = adapter.GetIPProperties();' có cần thiết không? – Joel

+0

@ Joel Không có dòng này là không cần thiết dựa trên thử nghiệm Tôi chỉ chạy trên hộp dev của tôi. Đã cập nhật câu trả lời để phản ánh thử nghiệm của tôi. – jordanhill123

Các vấn đề liên quan