PDA

You are currently viewing a search engine-friendly (archive) version of this page.

View Full Version : Randomizing values in VC++


scatman
December 8, 2001, 12:30 pm
Hi,
I'm using VC++ to randomize a number but every time I do it I get the same number. How would I get a different number each time I randomize?

The code that I'm using right now is:

int SOURCE_PORT = (rand() % 3000)+ 1000;

However, each time I use this function the number I get is 1041.

Also, is there a function that allows you to randomize a number between 2 different numbers, such as from 2000 to 6000?
With rand() you can only randomize a number from 0. I appreciate the help. Thanks!

Tonker
December 11, 2001, 12:47 pm
Try using the srand() function. This allows you to seed the random number generation function with a number. I think it's generally used with a function to grab the system time as an integer. Then call the rand() function.

take a peek at this link:
<a href="http://www.cprogramming.com/fod/srand.html" target="_blank">http://www.cprogramming.com/fod/srand.html</a>

Tonker
December 11, 2001, 12:50 pm
BTW, if you're just trying to grab yourself a port for a server, there's a function available to request that the OS give you the next available port.

scatman
December 13, 2001, 02:30 pm
Hey Tonker, what is that function that finds an available port automatically that you were talking about? Thanks for the help. :)

Tonker
December 13, 2001, 04:29 pm
Take a peek at this link, here's where I found it:
<a href="http://www.ecst.csuchico.edu/~beej/guide/net/html/" target="_blank">http://www.ecst.csuchico.edu/~beej/guide/net/html/</a>

It's not actually a function, but if you set the port field in the the structure passed to the bind() function to 0, then it should get a random available port number for you.

If you're doing network programing, that link should help you. Also take a look at this one that covers networking specific to Windows.
<a href="http://world.std.com/~jimf/papers/sockets/winsock.html" target="_blank">http://world.std.com/~jimf/papers/sockets/winsock.html</a>

scatman
December 14, 2001, 06:44 pm
Thanks a whole bunch Tonker!
You're always a huge help. :)