Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get Computer's MAC address "OFFLINE"

Tags:

c#

mac-address

Is there any way to get computer's mac address when there is no internet connection in c#? I'am able to get when I have connection but not able to get when I am offline. But strongly I need the mac address for my work.

My online code;

var macAddr =
      (from nic in NetworkInterface.GetAllNetworkInterfaces()
       where nic.OperationalStatus == OperationalStatus.Up
       select nic.GetPhysicalAddress().ToString()).FirstOrDefault();
like image 285
Mehmet Ince Avatar asked Apr 03 '13 09:04

Mehmet Ince


2 Answers

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

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

Slightly modified from How to get the MAC address of system - C-Sharp Corner

like image 191
jordanhill123 Avatar answered Oct 05 '22 11:10

jordanhill123


You can use WMI in C# (System.Management) to get a list of Win32_NetworkAdapter's which contains a MACAddress property.

http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394216(v=vs.85).aspx

like image 40
PhonicUK Avatar answered Oct 05 '22 11:10

PhonicUK