logo

English

이곳의 프로그래밍관련 정보와 소스는 마음대로 활용하셔도 좋습니다. 다만 쓰시기 전에 통보 정도는 해주시는 것이 예의 일것 같습니다. 질문이나 오류 수정은 siseong@gmail.com 으로 주세요. 감사합니다.

[C/C++] Random UUID String 생성 코드

by digipine posted Oct 21, 2021
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>

int get_nonce(void) {
    /* add your random nonce int value for more secure protection */
    return 289182;
}

int random_int() {
	unsigned int nonce = (unsigned int)time(NULL) & get_nonce(); 
	srand(nonce);
	return rand();
}

uint64_t random_uint64(void) {
	uint64_t num = random_int() & 0x1FFFFF;
	num = (num << 32) | random_int();
	return num;
}

char *random_uuid(void) {
	const char *template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
	const char *samples = "0123456789abcdef";
	union { unsigned char b[16]; uint64_t word[2]; } rnd;
	rnd.word[0] = random_uint64();
	rnd.word[1] = random_uint64();
	/* Generate the string */
	char uuid[37], *dst = uuid;
	const char *p = template;
	int i = 0, n = 0;
	while(*p) {
		n = rnd.b[i >> 1];
		n = (i & 1) ? (n >> 4) : (n & 0xf);
		switch (*p) {
			case 'x':
				*dst = samples[n];
				i++;
				break;
			case 'y':
				*dst = samples[(n & 0x3) + 8];
				i++;
				break;
			default:
				*dst = *p;
		}
		p++;
		dst++;
	}
	uuid[36] = '\0';
	return strdup(uuid);
}

int main(int argc, char *argv[]) {
	char *tmp_uid = random_uuid();
	printf("make uuid : %s\n", tmp_uid); 
	free(tmp_uid);
	return 0;
}

TAG •

List of Articles
No. Subject Author Date Views
» [C/C++] Random UUID String 생성 코드 digipine 2021.10.21 1302
22 소켓 통신을 이용한 HTTP 서버 개발 강의록 file digipine 2020.08.01 1482
21 C++ Atomic 클래스에 대해서 file 엉뚱도마뱀 2017.12.13 2139
20 C++ 컴파일 오류(error): variable 'std::istringstream sstream' has initializer but incomplete type digipine 2017.11.02 21077
19 fopen 파일 열기 모드 옵션 정리 digipine 2017.11.02 3894
18 make -j 옵션으로 컴파일 속도 최적화 하기 digipine 2017.11.01 2759
17 [Linux] Pthread 사용법, Thread 동기화 총정리 digipine 2017.11.01 294048
16 [linux] zlib build 방법 digipine 2017.11.01 1483
15 Linux C 언어로 Shell 명령어 실행하기 digipine 2017.11.01 22587
14 Introduce to Singly-linked List file digipine 2017.11.01 1288
13 [shared lib] so 동적 라이브러리 만들기와 사용법 - 리눅스 digipine 2017.11.01 6434
12 Unix C/C++ Input and Output Function Reference digipine 2017.11.01 88073
11 wchar_t에 대하여 digipine 2017.11.01 7343
10 C 에서 Overloading 구현 digipine 2017.11.01 1790
9 C를 이용한 객체지향 프로그래밍 digipine 2017.11.01 568
8 Callback in C++ 와 Delegate 차이점 digipine 2017.11.01 2525
7 Solaris에서 pmap을 이용하여 백그라운드 프로세스 메모리 크기 구하기 digipine 2017.10.29 28598
6 Solaris 10에 개발 Tool (gcc,vim,gdb) 설치 digipine 2017.10.29 1257
5 brute-force 알고리즘을 이용한 패턴 위치 찾기 digipine 2017.10.29 1501
4 MD5 파일 변조 검사 관련 소스 (리눅스/Windows) digipine 2017.10.29 2613
Board Pagination Prev 1 2 Next
/ 2