I need fast way to generate ip numbers that are valid (reserved ips are valid too).
For now i am using this:
unsigned char *p_ip;
unsigned long ul_dst;
p_ip = (unsigned char*) &ul_dst;
for(int i=0;i<sizeof(unsigned long);i++)
*p_ip++ = rand()%255;
ip.sin_addr.s_addr = ul_dst;
But sometimes it generate non-valid numbers, but this code can generate about 10k of valid ips in a second. Can anyone contribute?
Thank you
calling rand() is probably the slowest part of your code, if you use the implementation of a random function found at http://en.wikipedia.org/wiki/Multiply-with-carry
This is an ultra fast C function for generating random numbers.
storing
sizeof(unsigned long)in a registered variable i.e.:register int size = sizeof(unsigned long)should also help slightly.
Since you are using 4 chars = 4 x 8 byte memory, you can instead use a 32bit integer which will only require one memory address.
combining the bitshifting, new random method, registered variables, should reduce running times by quite a bit.
Above this code I have the exact copy of the random function from wikipedia.
Hopefully this will run much faster.
We know the size of a 32bit int is 4*8 so no need for the sizeof anymore, and instead of %255 I replaced it with a 255 bit mask