Search code examples
cguiduuid

How to generate a GUID in C?


I want to generate guids to insert into a SQLite database (i.e. no support from the db itself). However, I would like to have control over certain properties:

  1. Orderedness for generating increasing guid values.
  2. Computer independence. The db is public and may/may not want guids to allow someone to trace data back to a specific machine.
  3. 'Enough' randomness. The guids are keys in the db which is going to be merged with a lot of other dbs and can get quite large, meaning that faking a guid like many algorithms do is no good.
  4. I can deal with using system specific APIs but please link both Windows and Linux functions, and something like SQLite is preferred, where I can just use code someone else wrote.
  5. I would also prefer code which is OK to use in a commercial application.

Solution

  • You can either use or look at the code of Boost.Uuid :

    http://www.boost.org/doc/libs/1_47_0/libs/uuid/index.html

    It is a C++ library, but still, you can find inside how the code author retrieved the Uuid on multiple systems. Last time I checked (january 2010), I found at least the following implementations for Windows and Linux/Solaris (this info could be outdated):

    UUID/GUID on Linux/Solaris

    Open a file to /dev/urandom and read enough bytes (16) to make up a GUID/UUID.

    UUID/GUID on Windows

    Use the following WinAPI functions

    Other implementations

    The Wikipedia page on GUID/UUID has a list of alternative implementations you could use/study:

    https://en.wikipedia.org/wiki/UUID#Implementations

    About your conditions

    There is a GUID/UUID type which is always random (the version 4), meaning that to be compatible with other GUID/UUID semantics, you should respect that.

    Now, you want the GUID/UUID to be ordered in time. The only way to do that without weakening the GUID/UUID randomness would be to prefix the 16-byte GUID/UUID with an unsigned integer (which would make your identifier data 20-bytes, or more, depending on your integer). Just generate a GUID/UUID, and increase the integer.