Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random UUIDs in Linux

Tags:

c++

linux

guid

uuid

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?

like image 693
themoondothshine Avatar asked Feb 01 '10 05:02

themoondothshine


People also ask

How are UUIDs generated Linux?

Most of the Linux/Unix system supports the command line utility tool uuidgen to generate the UUID. If the package is unavailable install using apt install uuid-runtime command. Uuidgen can generate random-based, time-based and hash-based UUIDs. Random based UUIDs is sufficient in most cases.

How random UUID is generated?

This version of UUID is generated randomly. Although the random UUID uses random bytes, four bits are used to indicate version 4, while two to three bits are used to indicate the variant. These can be created using a random or pseudo-random number generator.

How random are UUIDs?

A sample of 3.26*10¹⁶ UUIDs has a 99.99% chance of not having any duplicates. Generating that many UUIDs, at a rate of one per second, would take a billion years.

What is Uuidgen in Linux?

The uuidgen program creates (and prints) a new universally unique identifier (UUID) using the libuuid(3) library. The new UUID can reasonably be considered unique among all UUIDs created on the local system, and among UUIDs created on other systems in the past and in the future.


1 Answers

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
like image 69
themoondothshine Avatar answered Oct 07 '22 01:10

themoondothshine