I have this code:
static void Main(string[] args)
{
string f = "0.0.0";
Program c = new Program();
for(int i = 1; i < 255; i++)
{
Thread x = new Thread(() => c._scan(f, i.ToString()));
x.Start();
}
Console.WriteLine("Realizado con exito!");
Console.WriteLine("Escaneo realizado!\nEncontrados " + x + " hosts.");
}
Which executes this method:
public void _scan(string subred, string num)
{
Ping _ping;
PingReply _respuesta;
IPAddress _ip;
IPHostEntry _host;
string _subred = "." + num;
_ping = new Ping();
_respuesta = _ping.Send(subred + _subred, 900);
if (_respuesta.Status == IPStatus.Success)
{
try
{
_ip = IPAddress.Parse(subred + _subred);
_host = Dns.GetHostEntry(_ip);
x++;
Console.WriteLine( "Hostname: " + _host.HostName + " | " + "IP: " + _ip.ToString() + " | MAC: " + GetMacAddress(_ip.ToString()));
}
catch { Console.WriteLine("IP:" + subred + _subred + " | MAC: "+ GetMacAddress(subred + _subred) + " Se desconoce"); }
}
}
When I execute the with the thread it executes the same variable "i" more than once, but it does not always do it one after the other, look what it throws at me:
- Hostname: ---- | IP: 0.0.0.35 | MAC: -----
- Hostname: -- | IP: 0.0.0.56 | MAC: ----
- Hostname: --- | IP: 0.0.0.50 | MAC: ----
- Hostname: --- | IP: 0.0.0.56 | MAC: ----
- Hostname: --- | IP: 0.0.0.73 | MAC: ---
- Hostname: ---- | IP: 0.0.0.80 | MAC: --
There I only showed you the first 7 lines, but the repetitions are many more.
NOTE: WHEN I DO IT WITHOUT THE THREAD IT WORKS CORRECTLY, BUT I SHOULD NOT RUN THE PROGRAM WITHOUT A THREAD BECAUSE IT CAN TAKE 9 SECONDS FOR EACH ITEM, IMAGINE SCANNING 225 THINGS AND IT TAKES 9 SECONDS FOR EACH ONE.
The repetitions are the lines that were left in the buffer, so it repeats them. Try to flush the console after each WriteLine, you do it by calling:
Wow, I discovered the answer in a forum by accident. FONT
You must execute this before the Thread, this forces the Thread to be updated and thus the Buffer is clean. The reason for the duplication was that, the buffer still stored information and it had to be released, but with this method it is no longer.