Question

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();
Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top