C: Fill an array of unsigned integers with random data using getrandom()

Often I need to generate random unsigned integers for seeding PRNGs. The best way is using the getrandom() system function to read OS level randomness into your array.

#include <sys/random.h>
#include <errno.h>

// Read from system random filling up an array of u64s
int fill_urandom_u64(uint64_t *buf, size_t bytes) {
    unsigned char *p = (unsigned char *)buf;

    while (bytes > 0) {
        ssize_t n = getrandom(p, bytes, 0);
        if (n < 0) {
            if (errno == EINTR) { continue; }
            else { return -1; }
        }
        p     += n;
        bytes -= n;
    }

    return 0;
}

Declare your array of integers, and the pass it as a pointer to this function to fill with random bytes from your OS. This will get you a bunch of random integers you can use for seeding PRNGs.

uint64_t seed[4];
fill_urandom_u64(seed, sizeof(seed));


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 216.73.216.43
To prevent spam please submit by clicking the kitten: