[Lugge] generare numeri casuali in c usando /dev/random o /dev/urandom

  • From: Marco Antonietti <marco.antonietti@xxxxxxxxxxxxx>
  • To: lugge@xxxxxxxxxxxxx
  • Date: Tue, 01 Feb 2005 15:46:51 +0000

ho trovato un po di esempi:

uno è questo:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <assert.h>

int main ()
{

       char* str = (char*)malloc (8 * sizeof (char) + 1); // chiave

       int i, fd;

       assert (str != NULL);

       // apre un descrittore al file di dispositivo
       if ((fd = open ("/dev/random", O_RDONLY)) == -1) {
               printf ("Errore nell'apertura nel file di dispositivo.\n");
               goto error;
       }

       printf ("Chiave\t\t: ");

       // legge una stringa casuale
       for (i = 0; i < 8; i++) {
               read (fd, str, 1);
               printf ("%02x", *str++);
       }

       printf ("\n");

       close (fd);

error:
       free (str);

       exit (EXIT_SUCCESS);
}

e l'altro è questo:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>

main (void) {
int randnum;
int fd = open ("/dev/urandom", O_RDONLY);
if (fd != -1) {
read( fd, &randnum, 4 );
randnum = abs( randnum ); /* If you only want positive values */
printf("Random number : %d\n",randnum);
close(fd);
} else {
/* Please don't do this if you need cryptographic security! */
randnum = time(NULL) + getpid(); // + other weird stuff;
}
//seed_the_rng_function(randnum);
}


ma io vorrei generaro dei numeri compresi tra 0 e 255, per il momento ho creato una funzione seeder:


int randomseed(void){
int randnum;
int fd = open("/dev/urandom", O_RDONLY);
if (fd != -1) {
read(fd,&randnum,4);
randnum = abs(randnum); }
close(fd);
return randnum;
}


e poi la richiamo così: srand(randomseed());

poi genero i numeri con rand()%256;

ma non credo che sia il modo migliore...

per generare dei numeri tra 0 e 255 usando /dev/random o /dev/urandom come devo fare?

grazie in anticipo a tutti...

--
One Love!

public key on keyserver:
http://keyserver.linux.it/pks/lookup?op=index&exact=on&search=marleylandia
http://keyserver.linux.it/pks/lookup?op=index&exact=on&search=marco.antonietti


Other related posts:

  • » [Lugge] generare numeri casuali in c usando /dev/random o /dev/urandom