[clue-tech] $RANDOM quality.
David Anselmi
anselmi at anselmi.us
Sun Apr 17 13:51:27 MDT 2005
So I wanted to generate a random IP address. (Stop me if you've heard
this one... ;-) This is a story of some shell stuff I learned today
(since the lists have been pretty slow lately).
Turns out that bash has a $RANDOM that gives you random numbers. I
wonder how random it is?
So $(( $RANDOM % 256 )) (arithmetic expansion) gives you random numbers
suitable to fill a byte.
And printf "%.2x\n" will convert your numbers to hex so that xxd -r -p
can convert them into binary bytes.
Then you can pipe the binary to ent to see how random it is. Looks to
me like it's pretty close to the radio noise random.org uses. (Well, no
I didn't use a huge number of samples.)
Pretty cool.
My first try converted to hex with bc (obase=16, that's cool), once for
each number I got. Even after I figured out how to pipe all the numbers
through one bc it was still slow because I had to pad the leading zeros
myself. Switching to printf made it 3x faster.
So here's the code:
for i in $(seq 100000) ; do
printf "%.2x\n" $(( $RANDOM % 256 ))
done | xxd -r -p | ent
Of course $RANDOM is only 15 bits so:
printf "%.4x\n" $RANDOM
isn't very "good".
How's that for a way to turn a 5 minute (or less) "give me a random IP"
into an afternoon?
Dave
More information about the clue-tech
mailing list