如何使用c#获取mac os x设备的物理地址

问题描述 投票:-1回答:1

我正在使用visual studio for mac使用c#。我已经尝试过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地址以获得其唯一标识。

c# cocoa visual-studio-mac
1个回答
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

            }

        }
© www.soinside.com 2019 - 2024. All rights reserved.