My program is a multi threaded proxy checker and whenever I return the proxy ip addresses from my method and try to echo them out I'm getting a bunch and the threads are doing it completely unintended. It's supposed to supply each thread with a line of IP addresses. Here's a screenshot of what's echoing. After this the IP variable will return and contain null.
My plagued code (bear with me, based off a public example):
static List<String> ips = new List<String>();// this is at the start of the program class
static Random rnd = new Random();
private static String getip()
{
if (ips.Count == 0)
{
return null;
}
return ips[rnd.Next(0, ips.Count)];
}
Also the get IP is called in a while (true)
loop as it's a proxy checker, I don't think that code is too necessary.
The other code:
while (true)
{
string ip = getip();
try
{
using (var client = new ProxyClient(ip, user, pass))
{
Console.WriteLine(ip, user, pass);
client.Connect();
if (client.IsConnected)
{
return true;
}
else
{
client.Disconnect();
return false;
}
}
}
catch
{
removeip(ip);
}
Thread.Sleep(30);
}
For example, thread 1 should have 127.0.0.1 (first IP from list), thread 2, 127.0.0.2 (second IP from list) etc etc, the problem at the moment is located in the screenshot.
Edit: this is not a duplicate i didn't explain what i need properly, this note from Eric J explains what i'm trying to do, it wasn't just the random issue.
NOTE
If you want each thread to get its own unique IP rather than a random one, you'll need to do something different than pick a random IP. You can after all get the same random IP more than once (if you flip a coin twice, you might get head twice or tails twice).
A good strategy would be to start from your List<String> ips and create one thread for each entry in that list.