I write my first kernelmodul for manipulating network-traffic using netfilter.
Now i need a random number generator like rand() in stdlib.h.
Is there a rand-function for kernelmodules?
Can anyone help me?
Thanks a lot!
Try to look at the "include/linux/random.h", I hope it will help you
There is get_random_bytes(void *buf, int nbytes) at "linux/random.h".
And it generates random numbers! - Thank you!
But can anyone tell me how it works?
- Generates it numbers between 0 and 255 if nbytes = 1 ? (After first tests it seems so)
- And how random are the random numbers? (sounds stupid, but i hope you know what i mean :) )
Thanks a lot!
ps. sorry for my bad english
/usr/src/linux> grep get_random_bytes */*.c */*/*.c
drivers/char/random.c: * void get_random_bytes(void *buf, int nbytes);
drivers/char/random.c:void get_random_bytes(void *buf, int nbytes)
drivers/char/random.c: printk(KERN_NOTICE "get_random_bytes called before "
drivers/char/random.c: get_random_bytes(uuid_out, 16);
drivers/char/random.c: get_random_bytes(keyptr->secret, sizeof(keyptr->secret));
drivers/char/random.c: get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
<-- snip -->
Found it! So you have learned something today: if you need to find a function's implementation, grep for it yourself the next time.
The second line (with the "void" in front) looks like the implementation.
There are lengthy comments in the file.
Reading the implementation of get_random_bytes() (you are going to write kernel code, so it is safe to assume that you are able to read C (*)) and the comments about the other functions, the numbers are 'perfectly' random, which means on the other hand, that requesting them is slow. If you need many of them or a really high speed RNG, you can implement an own very simple one and reseed it periodically with get_random_bytes() to get better output.
(*) C is _designed_ to describe algorithms, so cleanly written C code is the best in-depth documentation you can get. _And_ you can be sure that it correctly documents the program's behaviour and is never out of date. Luckily open source programmers know that and try to produce readable (== maintainable) code.