如何使用C#获取Mac OS X设备的物理地址

时间:2018-08-20 12:45:26

标签: c# cocoa visual-studio-mac

我正在使用Visual C#在Mac上使用Visual Studio。我已经尝试了system.net.networkinformation,但是它给了我一个空白字符串。

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

这就是我用来获取Mac地址的方法。它在Windows桌面应用程序中工作正常,但在os x中不工作。我正在尝试获取mac桌面的mac地址,以获取其唯一标识。

1 个答案:

答案 0 :(得分:0)

以下功能提供了我需要的确切Mac地址。

  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

            }

        }