Search code examples
c#cocoavisual-studio-mac

How do i get Physical Address of a mac os x device by using c#


I am using visual studio for mac using c#. I have tried system.net.networkinformation but it gives me blank string.

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    mac += nic.GetPhysicalAddress().ToString();
                    //Console.WriteLine(mac);
                    break;
                }
            }

This is what i am using to get mac address. It works fine in windows desktop application but not working in os x. I am trying to get mac address of mac desktop for its unique identification.


Solution

  • Below function gives exact mac addresses which i need.

      public static string GetMacAddress()
            {
                System.Net.NetworkInformation.NetworkInterfaceType Type = 0;
                string MacAddress = string.Empty;
                try
                {
                    System.Net.NetworkInformation.NetworkInterface[] theNetworkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
                    foreach (System.Net.NetworkInformation.NetworkInterface currentInterface in theNetworkInterfaces)
                    {
                        Type = currentInterface.NetworkInterfaceType;
                        if (Type == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet || Type == System.Net.NetworkInformation.NetworkInterfaceType.GigabitEthernet || Type == System.Net.NetworkInformation.NetworkInterfaceType.FastEthernetFx)
                        {
                            MacAddress = currentInterface.GetPhysicalAddress().ToString();
                            break;
                        }
                    }
    
                    return MacAddress;
    
                }
                catch 
                {
                    // your code goes here
    
                }
    
            }