home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

3.2.158 srand



This function sets the random number seed for the rand operator. If EXPR is omitted, it does srand(time) , which is pretty predictable, so don't use it for security-type things, such as random password generation. Try something like this instead:[ 9 ]

[9] Frequently called programs (like CGI scripts) that simply use

time ^ $$

for a seed can fall prey to the mathematical property that

a^b == (a+1)^(b+1)

one-third of the time. If you're particularly concerned with this, see the Math::TrulyRandom module in CPAN.

srand( time() ^ ($$ + ($$ << 15)) );

Of course, you'd need something much more random than that for serious cryptographic purposes, since it's easy to guess the current time. Checksumming the compressed output of one or more rapidly changing operating system status programs is the usual method. For example:

srand (time ^ $$ ^ unpack "%32L*", `ps axww | gzip`);

Do not call srand multiple times in your program unless you know exactly what you're doing and why you're doing it. The point of the function is to "seed" the rand function so that rand can produce a different sequence each time you run your program. Just do it once at the top of your program, or you won't get random numbers out of rand !