Search code examples
c++linuxguiduuid

Generating random UUIDs in Linux


I am stuck in a strange predicament. I need to generate UUIDs in my Linux program (which I distribute using RPMs). I do not want to add another dependency to my application by requiring the user to install libuuid (seems like libuuid isn't included in most Linux distros, like CentOS).

Isn't there a standard Linux system call which generates UUIDs (like say, in Windows there CoCreateGuid)? What does the command uuidgen use?


Solution

  • Thanks for all your comments!

    I went through each one, and here's what suited my requirement the best:

    What I needed was just plain time-based UUIDs which were generated from random numbers once for every user who installed the application. UUID version 4 as specified in RFC 4122 was exactly it. I went through a the algorithm suggested, and came up with a pretty simple solution which would work in Linux as well as Windows (Maybe its too simplistic, but it does satisfy the need!):

    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