in reply to Generate a session ID
Check the rand function used by your version of Perl. Specifically, check for the number of randbits it is configured for:
P:\test>Perl -v This is perl, v5.8.7 built for MSWin32-x86-multi-thread (with 7 registered patches, see perl -V for more detail) ... P:\test>Perl -V:randbits randbits='15';
Which means that with AS perl, this snippet will only ever produce 32768 unique ids:
#! perl -slw use strict; my %cache; $cache{ sprintf("%0.8x",rand()*0xffffffff) } = undef for 1 .. 1_000_00 +0; printf "1 million attempts produced %d keys\n", scalar keys %cache; printf "between %s and %s\n", (sort keys %cache)[ 0, -1 ]; __END__ P:\test>junk 1 million attempts produced 32768 keys between 00000000 and fffdffff
I'm not sure what the mathematical probability is for picking duplicates from a pool 2^15 values, but in practice, it produces very, very few unique values before it repeats itself:
#! perl -slw use strict; my %cache; my $u = sprintf("%0.8x",rand()*0xffffffff); until( exists $cache{ $u } ) { $cache{ $u } = undef; $u = sprintf("%0.8x",rand()*0xffffffff); } printf "Produced %d unique keys before duplicating\n", scalar keys %ca +che; printf "between %s and %s\n", (sort keys %cache)[ 0, -1 ]; __END__ P:\test>junk Produced 454 unique keys before duplicating between 00bdffff and ff89ffff P:\test>junk Produced 273 unique keys before duplicating between 013dffff and feb5ffff P:\test>junk Produced 84 unique keys before duplicating between 0183ffff and fe5bffff P:\test>junk Produced 94 unique keys before duplicating between 001bffff and fbc1ffff
You can extend the range almost linearly by multiplying two calls to rand:
#! perl -slw use strict; my %cache; $cache{ sprintf( "%0.8x", rand() * rand() * 0xffffffff ) } = undef for + 1 .. 1_000_000; printf "1 million attempts produced %d keys\n", scalar keys %cache; printf "between %s and %s\n", (sort keys %cache)[ 0, -1 ]; __END__ P:\test>junk 1 million attempts produced 994758 keys between 00000000 and ffae0137
but even then, the number of uniques you will get before repeats is dismally low:
Produced 17891 unique keys before duplicating between 00000000 and fba0116f P:\test>junk Produced 1957 unique keys before duplicating between 0008e633 and fb575407 P:\test>junk Produced 30229 unique keys before duplicating between 00000000 and fdeaed07 P:\test>junk Produced 10830 unique keys before duplicating between 0000eedf and ff441eff P:\test>junk Produced 15537 unique keys before duplicating between 00000000 and fe068a77
All in all, a better session id generator than this would be strongly advisable.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Generate a session ID
by thor (Priest) on Dec 03, 2005 at 17:21 UTC | |
|
Re^2: Generate a session ID
by Spidy (Chaplain) on Dec 04, 2005 at 19:28 UTC | |
by Happy-the-monk (Canon) on Dec 04, 2005 at 19:41 UTC | |
by Your Mother (Archbishop) on Dec 04, 2005 at 21:46 UTC | |
by Spidy (Chaplain) on Dec 05, 2005 at 02:30 UTC |