3 ms·
If I were to use C, what should I be using instead of rand(3)? A cursory look at rand(3) SEE ALSO hints at candidates but random(3) seems to hardly fare better
by lloeki 12y ago
If I were to use C, what should I be using instead of rand(3)?
A cursory look at rand(3) SEE ALSO hints at candidates but random(3) seems to hardly fare better†, arc4random(3) isn't available on glibc.
† A few notes about rand as the parent suggests, but nothing regarding mod bias, srandom initial state, or threads:
> It returns successive pseudo-random numbers in the range from 0 to (231)-1. The period of this random number generator is very large, approximately 16((2*31)-1).
> All of the bits generated by random() are usable. For example, `random()&01' will produce a random binary value.
- justincormack 12y agoarc4random (under a different name as the name is misleading) will be standardised, and Linux now has a random() syscall that is a necessary building block, so it doesnt fail. In the meantime, use arc4random on openbsd and netbsd 7 and read from /dev/urandom on all other platforms (FreeBSD is in process of fixing arc4random, currently still uses rc4 and may have problems with state being same in multiple threads; I guess OSX is the same version). Android does have arc4random, although it can fall back to weaker random sources if it does not manage to open /dev/urandom https://code.google.com/p/android-source-browsing/source/browse/libc/bionic/arc4random.c?repo=platform--bionic&r=3a654b1e04d4275ae315cfe1b196998acf10052c https://code.google.com/p/android-source-browsing/source/bro...
- tedunangst 12y agoThere are several paths to getting arc4random or something like it. You can just use it and optionally tell people to link with e.g. libcrypto from libressl. You can include the portable code yourself, though that's yucky. Aging software that includes never updated very early versions of arc4random is actually kind of a problem because that code still gets used when better versions are available. You can link with https://github.com/nmathewson/libottery-lite https://github.com/nmathewson/libottery-lite which is approximately arc4random with a different name. Some combination of the above. For example, sqlite3 includes an arc4random workalike (rc4 rng), but doesn't discard the early stream (critical because it leaks the key) nor include any degree of fork safety. Nor does it check if the host provides a better version. sqlite3 shipped with OpenBSD is patched to use libc arc4random instead, but building from source means you're back to square one. Not a big deal in the case of sqlite3, but try not to build something that doesn't improve as the world around it improves.
- noselasd 12y agoHow well does the rand48 family of functions fare ? http://pubs.opengroup.org/onlinepubs/7908799/xsh/drand48.html http://pubs.opengroup.org/onlinepubs/7908799/xsh/drand48.htm...