且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#(Mono)在Mac上获取唯一的系统ID

更新时间:2023-12-03 23:10:34

首先,不要使用MAC地址,因为这些地址可能会更改(欺骗或硬件更改),并且自10.3/4以来这不是Mac'ie的方式吗? ...从那时起,"I/O Kit注册表"是获取系统ID的首选方法.放到cmd行和man ioreg以获得相同的详细信息.

First, stay away from using a MAC address as those can change (spoofed or hardware change) and is not a very Mac'ie way since 10.3/4?... Since then the "I/O Kit registry" is the preferred method to get a system id. Drop to a cmd line and man ioreg for same details.

因此,不确定是否正在使用Xamarin.Mac,因此如果您,则可以绑定IOKit IORegistryEntryFromPath/IORegistryEntryCreateCFProperty API,因为我认为这些API当前不在C#中包装器,但是我真正使用的快速方法是:

So, not sure if you are using Xamarin.Mac or not, so if you are you could do a binding of the IOKit IORegistryEntryFromPath/IORegistryEntryCreateCFProperty APIs as I do not believe those are currently in C# wrappers, but really quick way that I use is:

using System;
using System.Diagnostics;
using System.Text;

namespace uuidmac
{
    class MainClass
    {
        static string MacUUID ()
        {
            var startInfo = new ProcessStartInfo () {
                FileName = "sh",
                Arguments = "-c \"ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/'\"",
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                UserName = Environment.UserName
            };
            var builder = new StringBuilder ();
            using (Process process = Process.Start (startInfo)) {
                process.WaitForExit ();
                builder.Append (process.StandardOutput.ReadToEnd ());
            }
            return builder.ToString ();
        }

        public static int Main (string[] args)
        {
            Console.WriteLine (MacUUID ());
            return 0;
        }
    }
}

示例输出:

 "IOPlatformUUID" = "9E134619-9999-9999-9999-90DC147C61A9"

如果您想要一些人类可读的内容,并且有人可以在关于本机"的主对话框中找到用于技术支持的电话,则还可以解析"IOPlatformSerialNumber"而不是"IOPlatformUUID".

You could also parse out "IOPlatformSerialNumber" instead of the "IOPlatformUUID" if you want something human readable and that someone can find on the main dialog of "About This Mac" for tech support calls...

现在,如果您要像在MS DPAPI中那样存储和保护信息,则可以使用KeyChain(OSX/iOS). Mono确实有一些基于x-plat的DPAPI加密api.

Now if you are looking at storing and protecting info as in the MS DPAPI, the KeyChain is the place to do that (OSX/iOS). Mono does have some of the DPAPI crypto apis that are x-plat based.