我知道这里已经讨论过这类问题:How to generate a random number in C?
但我想分享我实施它的方式只是为了知道人们可能会怎么想。
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
long int getNanoSecs(){
struct timespec unixtimespec;
clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
return unixtimespec.tv_nsec;
}
。 。
unsigned char personal_final_token[PERSONAL_FINAL_TOKEN_SIZE_SIZE];
unsigned char pwd_ptr_ctr;
srandom(getNanoSecs()*(getNanoSecs()&0xFF));
for(pwd_ptr_ctr=0;pwd_ptr_ctr<PERSONAL_FINAL_TOKEN_SIZE_SIZE;pwd_ptr_ctr++){
memset(personal_final_token+pwd_ptr_ctr,(random()^getNanoSecs())&0xFF,1);
}
只需定义PERSONAL_FINAL_TOKEN_SIZE_SIZE即可生成所需大小的随机标记。
答案 0 :(得分:1)
小心你的时钟源,否则你可能会得到意想不到的结果:
#include <stdio.h>
#include <linux/time.h>
#define SAMPLES 10
long getNanoSecs(){
struct timespec unixtimespec;
clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
return unixtimespec.tv_nsec;
}
int main (int argc, char* argv[]) {
int i;
long clocks[SAMPLES];
for (i = 0; i < SAMPLES; i++)
clocks[i] = getNanoSecs();
for (i = 0; i < SAMPLES; i++)
printf("%lu\n", getNanoSecs());
return 0;
}
[tbroberg @ www src] $ ./a.out 727544983 728544969 728544969 728544969 728544969 728544969 728544969 728544969 728544969 728544969
答案 1 :(得分:0)
你是对的,我想补充一点,我将CLOCK_REALTIME_COARSE
修改为CLOCK_REALTIME
按照linux man:
“CLOCK_REALTIME 系统范围的时钟,用于测量实际(即挂钟)时间。设置此时钟需要适当的权限。此时钟受系统时间不连续跳转(例如,系统管理员手动更改时钟)以及adjtime(3)和NTP执行的增量调整影响。
CLOCK_REALTIME_COARSE(自Linux 2.6.32起;特定于Linux) CLOCK_REALTIME的更快但不太精确的版本。当您需要非常快速但不是细粒度的时间戳时使用。“
但是,谢谢您的YOUR_TIME:)