SAndip Malla
SAndip Malla

Reputation: 1

How do I retrieve only Ethernet MAC Address in C#

I want to get MAC address of Ethernet Only but It sometime shows Wifi MAC Address too.

I Tried this code and while debugging I found out PC used only Wifi Network Interface Type. But whenever Ethernet is unplugged the code works. Network Interface Type changes to ethernet itself.

public static PhysicalAddress GetMacAddress()
{
       foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
       {
           // Only consider Ethernet network interfaces
           if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) 
           {
               return nic.GetPhysicalAddress();
           }
           else
           {
               MessageBox.Show("Error ", "Error!");
               Environment.Exit(1);
           }
       }
       return null;
}

Upvotes: 0

Views: 2239

Answers (1)

It all makes cents
It all makes cents

Reputation: 4983

As long as the computer has a LAN (ethernet) adapter installed and the adapter isn't disabled, it will show up regardless of whether or not it is connected (has an IP address). If you only want to get the MAC address if it is connected then do the following:

using System.Net.NetworkInformation;

public static PhysicalAddress GetMacAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        // Only consider Ethernet network interfaces
        if ((nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet || nic.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet) && nic.OperationalStatus == OperationalStatus.Up)
        {
            return nic.GetPhysicalAddress();
        }
        else
        {
            MessageBox.Show("Error ", "Error!");
            Environment.Exit(1);
        }
    }
    return null;
}

See also

Upvotes: 1

Related Questions