Linux 随机数
在 Linux 系统编程中,你经常会遇到需要生成随机数的场景,比如加密通信、数据模拟、游戏开发、验证码生成等等。Linux 提供了多种方式来生成随机数,不同的方法适用于不同的应用场景。
本文将带你系统学习:
rand()
和srand()
的用法;/dev/random
和/dev/urandom
的区别;getrandom()
系统调用;- 使用 OpenSSL 和其他加密安全库获取高质量随机数。
使用 rand() 生成伪随机数
rand()
是最常用的伪随机数函数,来自 <stdlib.h>
。
#include <stdio.h>
#include <stdlib.h>
int main() {
// 每次运行程序输出都是一样的
printf("随机数:%d\n", rand());
return 0;
}
如果你想让每次运行程序都输出不同的结果,可以使用 srand()
设置种子(seed):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // 用当前时间初始化种子
for (int i = 0; i < 5; i++) {
printf("随机数:%d\n", rand() % 100); // 取模控制范围:0~99
}
return 0;
}
注意
⚠️ rand()
的随机性较弱,不适用于安全场景,比如密码、加密密钥等。
读取 /dev/random 和 /dev/urandom
Linux 提供了两个特殊的设备文件:
/dev/random
:阻塞式,熵池不足时会等待;/dev/urandom
:非阻塞式,用伪随机扩展。
你可以直接从这些文件中读取高质量的随机数据:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
perror("打开 /dev/urandom 失败");
return 1;
}
unsigned char buffer[16];
read(fd, buffer, sizeof(buffer));
close(fd);
printf("生成的 16 字节随机数:\n");
for (int i = 0; i < 16; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
return 0;
}