[C언어] UUID 생성



UUID란?


universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. 

The term globally unique identifier (GUID) is also used, typically in software created by Microsoft.

(출처 : https://en.wikipedia.org/wiki/Universally_unique_identifier#Implementations)



rfc에 UUID에 대한 Spec이 있네요.


https://www.ietf.org/rfc/rfc4122.txt




<Java : UUID 생성>


Java의 경우에는 UUID를 생성하는 API가 제공되며, 아래와 같이 간단하게 구현 가능합니다.


import java.util.UUID;


String test_uuid = UUID.randomUUID().toString();



<C언어 : uuid 라이브러리로 UUID 생성>


C언어의 경우, uuid 라이브러리가 제공되어지는 경우가 있습니다.

이런 경우에는 아래와 같이 간단하게 구현 가능합니다. uuid.h


#include <uuid/uuid.h>


char test_uuid[37];


uuid_t uuidGenerated;

uuid_generate_random(uuidGenerated);

uuid_unparse(uuidGenerated, test_uuid);


생성 결과 예제 : 1dd3ea30-28e4-4813-be55-0c5bd8d18470

 => uuid_generate_random()를 사용하였기 때문에, version 4 UUID로 생성된 것으로 판단됩니다.


<<주의>> uuid 라이브리를 링크 옵션에 추가하지 않을 경우, 아래와 같은 error가 발생할 수 있습니다.


error: undefined reference to `uuid_generate_random'

error: undefined reference to `uuid_unparse'

error: collect2: error: ld returned 1 exit status



<C언어 : UUID 생성 함수 구현>


uuid 라이브러리가 제공되어지는 경우는 다음과 같이 직접 함수를 구현하여 사용 가능합니다.

아래 페이지의 내용을 참조하여, 제 입맛에 맞게 살짝 수정해 보았습니다.


(https://stackoverflow.com/questions/7399069/how-to-generate-a-guid-in-c)


#include <stdlib.h>


void generateUUID( char *pUUID )

{

int t = 0;

char *szTemp = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";

char *szHex = "0123456789abcdef-";

int nLen = strlen (szTemp);



srand (clock());

for (t=0; t<nLen; 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;

default : 

break;

}

pUUID[t] = c;

}

pUUID[t] = 0;

}


<C언어 : UUID 생성 함수 구현>


아래 페이지에 javascript로 구현한 예제가 있네요. 


https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript


For an RFC4122 version 4 compliant solution, this one-liner(ish) solution is the most compact I could come up with.:


function uuidv4() {

  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {

    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);

    return v.toString(16);

  });

}


console.log(uuidv4())


반응형

+ Recent posts