Search code examples
c#mac-address

Why am I getting an empty string when I try to get my MAC address?


I am trying to acquire my system's MAC address programmatically. I am writing in C#, using a Visual Studios .NET framework on a Windows 10 OS. I have included the System.Net.NetworkInformation namespace (for other .NET novices out there like myself, had to manually add it in the "References" section under the Solution Explorer, then use the "using" keyword). To get the MAC Address, I am using the following code:

try
{
    var macAddr =
        (
            from nic in NetworkInterface.GetAllNetworkInterfaces()
            where nic.OperationalStatus == OperationalStatus.Up
            select nic.GetPhysicalAddress().ToString()
        ).FirstOrDefault();
    Console.WriteLine("MAC address is: {0}", macAddr);

}
catch (Exception e)
{
    Console.WriteLine("Could not collect MAC Address;\nERROR: {0}", e);
}

The output that I am expecting is either:

Attempting to collect MAC Address...

MAC address is: XXXXXXXXXXXX

Where XXX.... is the 12-character MAC address, or:

Attempting to collect MAC Address...

Could not collect MAC Address;

ERROR: [error report inserted here]

What I am getting, however, is this:

Attempting to collect MAC Address...

MAC address is:

where the macAddr variable appears to have collected an empty string.

So... my question is, why am I getting an apparently empty string instead of the 12-character MAC address that I was expecting?


Solution

  • You're getting the empty MAC address of your Software Loopback Interface 1.
    Make sure you have an active connection with a network before attempting to run this code. Active meaning that the interface is activated (up) and connected to a network with either a DHCP given IP address or a static one.

    Loopback Device

    To fix this, you can simply remove all Loopback Interfaces from your query via

    var macAddresses = from nic in NetworkInterface.GetAllNetworkInterfaces()
                       where nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback
                       select nic.GetPhysicalAddress().ToString();
    

    Edit, you could do a check regardless of the OperationalStatus of your NICs and simply "ask" for non-empty MAC addresses:

    var macAddresses = from nic in NetworkInterface.GetAllNetworkInterfaces()
                       where !string.IsNullOrEmpty(nic.GetPhysicalAddress().ToString())
                       select nic.GetPhysicalAddress().ToString();