很多朋友經常用srand/rand產生隨機數, 其實這種隨機性並不好, 容易遭受攻擊(很多時候, 也滿足不了需求)。 在本文中, 我們來簡要介紹一下利用Linux的/dev/urandom文件產生較好的隨機數, 直接上代碼吧:
- #include <stdio.h>
- #include <fcntl.h>
- int main()
- {
- int randNum = 0;
- int fd = open("/dev/urandom", O_RDONLY);
- if(-1 == fd)
- {
- printf("error\n");
- return 1;
- }
- read(fd, (char *)&randNum, sizeof(int));
- close(fd); // 千千萬萬不要漏, 我曾漏過, 結果好悲劇
- printf("randNum is %d\n", randNum);
- return 0;
- }
結果:
randNum is -1061686095
[taoge@localhost learn_c]$ ./a.out
randNum is 1768060870
[taoge@localhost learn_c]$ ./a.out
randNum is -1313095365
[taoge@localhost learn_c]$ ./a.out
randNum is -1651791231
[taoge@localhost learn_c]$ ./a.out
randNum is 932742445
[taoge@localhost learn_c]$ ./a.out
randNum is 1191576271
[taoge@localhost learn_c]$
除了/dev/urandom還, 實際上還有一個/dev/random, 兩者是有一些小區別的, 有興趣的話, 大家可以在網上搜索並瞭解一下, 我就不再重複囉嗦了
http://blog.csdn.net/stpeace/article/details/45829161