在Linux中生成随机UUID

the*_*ine 11 c++ linux uuid guid

我陷入了一种奇怪的困境.我需要在我的Linux程序中生成UUID(我使用RPM分发).我不想通过要求用户安装libuuid来为我的应用程序添加另一个依赖项(似乎libuuid不包含在大多数Linux发行版中,如CentOS).

是不是有一个标准的Linux系统调用生成UUID(比如在Windows中有CoCreateGuid)?uuidgen使用的命令是什么?

VMc*_*ron 15

我错过了什么吗?你不能:

cat /proc/sys/kernel/random/uuid
Run Code Online (Sandbox Code Playgroud)

  • 可能无法移植到其他 Linux 系统。 (2认同)

the*_*ine 8

谢谢你们的评论!

我经历了每一个,这是最符合我要求的:

我需要的只是简单的基于时间的UUID,它是由安装应用程序的每个用户的随机数生成的.RFC 4122中指定的UUID版本4就是它.我完成了一个建议的算法,并提出了一个非常简单的解决方案,可以在Linux和Windows中使用(也许它太简单了,但它确实满足了需要!):

srand(time(NULL));

sprintf(strUuid, "%x%x-%x-%x-%x-%x%x%x", 
    rand(), rand(),                 // Generates a 64-bit Hex number
    rand(),                         // Generates a 32-bit Hex number
    ((rand() & 0x0fff) | 0x4000),   // Generates a 32-bit Hex number of the form 4xxx (4 indicates the UUID version)
    rand() % 0x3fff + 0x8000,       // Generates a 32-bit Hex number in the range [0x8000, 0xbfff]
    rand(), rand(), rand());        // Generates a 96-bit Hex number
Run Code Online (Sandbox Code Playgroud)


Che*_*aoh 7

我找到的一个好方法(对于linux dev)是#include <uuid/uuid.h>.然后你可以调用一些函数:

void uuid_generate(uuid_t out);
void uuid_generate_random(uuid_t out);
Run Code Online (Sandbox Code Playgroud)