Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a GUID in C?

Tags:

c

guid

uuid

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.
like image 787
chacham15 Avatar asked Dec 10 '22 06:12

chacham15


1 Answers

One place to look for an answer to creating a GUID that contains many of the elements the author is looking for is in PHP .. http://us3.php.net/uniqid .. In their examples, they discuss how to add server names, database names, and other elements to a GUID.

However, to address the need for a C based GUID function, here is code based on a JavaScript function .. Create GUID / UUID in JavaScript? .. this example uses RegEx to create the GUID.

Below is code that will create a GUID based on the JavaSCript example. I'm sure there are more elegant solutions out there. This is something cobbled together to help give a clean example for others to follow.

srand (clock());
char GUID[40];
int t = 0;
char *szTemp = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
char *szHex = "0123456789ABCDEF-";
int nLen = strlen (szTemp);

for (t=0; t<nLen+1; t++)
{
    int r = rand () % 16;
    char c = ' ';   

    switch (szTemp[t])
    {
        case 'x' : { c = szHex [r]; } break;
        case 'y' : { c = szHex [r & 0x03 | 0x08]; } break;
        case '-' : { c = '-'; } break;
        case '4' : { c = '4'; } break;
    }

    GUID[t] = ( t < nLen ) ? c : 0x00;
}

printf ("%s\r\n", GUID);

Note: strings end with a 0x00 character.

like image 76
E Net Arch Avatar answered Dec 31 '22 04:12

E Net Arch