Search code examples
cuuid

Generating a random UUID in C


How would I go about generating an entropy-based UUID in C and storing it as a string (char pointer)?

I'm hoping that there is an easy way to do this internally, but system("uuidgen -r") will work if not.


Solution

  • This functionality is provided by libuuid. (Packages libuuid1 and uuid-dev on Debian.)

    This is a simple program that generates an entropy-based (random) UUID and writes it to stdout, then exits with status 0.

    /* For malloc() */
    #include <stdlib.h>
    /* For puts()/printf() */
    #include <stdio.h>
    /* For uuid_generate() and uuid_unparse() */
    #include <uuid/uuid.h>
    
    
    /* Uncomment to always generate capital UUIDs. */
    //#define capitaluuid true
    
    /* Uncomment to always generate lower-case UUIDs. */
    //#define lowercaseuuid true
    
    /*
     * Don't uncomment either if you don't care (the case of the letters
     * in the 'unparsed' UUID will depend on your system's locale).
     */
    
    
    int main(void) {
        uuid_t binuuid;
        /*
         * Generate a UUID. We're not done yet, though,
         * for the UUID generated is in binary format 
         * (hence the variable name). We must 'unparse' 
         * binuuid to get a usable 36-character string.
         */
        uuid_generate_random(binuuid);
    
        /*
         * uuid_unparse() doesn't allocate memory for itself, so do that with
         * malloc(). 37 is the length of a UUID (36 characters), plus '\0'.
         */
        char *uuid = malloc(37);
    
    #ifdef capitaluuid
        /* Produces a UUID string at uuid consisting of capital letters. */
        uuid_unparse_upper(binuuid, uuid);
    #elif lowercaseuuid
        /* Produces a UUID string at uuid consisting of lower-case letters. */
        uuid_unparse_lower(binuuid, uuid);
    #else
        /*
         * Produces a UUID string at uuid consisting of letters
         * whose case depends on the system's locale.
         */
        uuid_unparse(binuuid, uuid);
    #endif
    
        // Equivalent of printf("%s\n", uuid); - just my personal preference
        puts(uuid);
    
        return 0;
    }
    

    uuid_unparse() doesn't allocate it's own memory; to avoid a segmentation fault upon execution you must do that with manually with uuid = malloc(37); (you can also store the UUID in a char array of that length: char uuid[37];). Make sure to compile with -luuid so that the linker knows that uuid_generate_random() and uuid_unparse() are defined in libuuid.