在C中生成随机UUID

时间:2018-06-27 02:08:27

标签: c uuid

如何在C语言中生成基于熵的UUID并将其存储为字符串(字符指针)?

我希望有一个简单的内部方法,但是system("uuidgen -r")可以解决这个问题。

2 个答案:

答案 0 :(得分:4)

libuuid提供了此功能。 (在Debian上打包libuuid1uuid-dev。)

这是一个简单的程序,它生成基于熵的(随机)UUID,并将其写入stdout,然后以状态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()不会分配自己的内存;为了避免执行时出现分段错误,您必须使用uuid = malloc(37);手动进行操作(您也可以将UUID存储在长度为char uuid[37];的char数组中)。确保使用-luuid进行编译,以使链接器知道uuid_generate_random()中定义了uuid_unparse()libuuid

答案 1 :(得分:0)

在 Linux 上,您可以使用 ,在 Ubuntu 20.x 上,它位于 /usr/include/uuid/。

/* uuid.c
 * 
 * Defines function uuid
 *
 * Print a universally unique identifer, created using Linux uuid_generate.
 *
 * 
 * Compile
 *
 * gcc uuid.c -o uuid -luuid -Wall -g
 *
 *
 * Run
 * 
 * ./uuid
 * 
 *
 * Debug
 *
 * gdb uuid
 * b main
 * r
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <uuid/uuid.h>

char* uuid(char out[UUID_STR_LEN]){
  uuid_t b;
  uuid_generate(b);
  uuid_unparse_lower(b, out);
  return out;
}

int main(){
  char out[UUID_STR_LEN]={0};
  puts(uuid(out));
  return EXIT_SUCCESS;
}