I want to use /dev/random or /dev/urandom in C. How can I do it? I don’t know how can I handle them in C, if someone knows please tell me how. Thank you.
I want to use /dev/random or /dev/urandom in C. How can I do it?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In general, it’s a better idea to avoid opening files to get random data, because of how many points of failure there are in the procedure.
On recent Linux distributions, the
getrandomsystem call can be used to get crypto-secure random numbers, and it cannot fail ifGRND_RANDOMis not specified as a flag and the read amount is at most 256 bytes.As of October 2017, OpenBSD, Darwin and Linux (with
-lbsd) now all have an implementation ofarc4randomthat is crypto-secure and that cannot fail. That makes it a very attractive option:Otherwise, you can use the random devices as if they were files. You read from them and you get random data. I’m using
open/readhere, butfopen/freadwould work just as well.You may read many more random bytes before closing the file descriptor. /dev/urandom never blocks and always fills in as many bytes as you’ve requested, unless the system call is interrupted by a signal. It is considered cryptographically secure and should be your go-to random device.
/dev/random is more finicky. On most platforms, it can return fewer bytes than you’ve asked for and it can block if not enough bytes are available. This makes the error handling story more complex: