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.
/proc/sys/kernel/random/uuid is a type 4 (random) UUID with certain semantics - it's not just a string of random hex characters. For example you'll see the first digit in the third group is always a 4.
A UUID (Universal Unique Identifier) is a 128-bit value used to uniquely identify an object or entity on the internet. Depending on the specific mechanisms used, a UUID is either guaranteed to be different or is, at least, extremely likely to be different from any other UUID generated until A.D. 3400.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With