I write ip/port scanner so users using search on our LAN know if the particular ftp is online or not.
The class I write has the following structure:
I use that class as
But Joins work synchronously in that sense that the next Join in the for-loop executes only after previous one returns. So the scan of one address range consumes very much time. I test it using only 4 adresses I sure are offline and trying to Join to 5 threads. I receive the null reference error only after 1-2 minutes of executing of program.
But the following code works fine and returns in 10 seconds (this code is met often in google but applied not to sockets):
What is the problem with sockets? I use asp.net2 and IIS 7 on Vista 64. (I tried the same in winform application with the same results.)
Thank you.
The class I write has the following structure:
Code:
public class IPScanner
{
public IPScanner() { }
private void connect(object data)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect((string)data, 21);
}
catch { }
finally
{
socket.Close();
}
}
public void Scan()
{
Thread[] threads = new Thread[255];
for (int i = 0; i < 255; i++)
{
threads[i] = new Thread(new ParameterizedThreadStart(connect));
threads[i].Start( "xxx.xxx.xxx." + ((int)(i+1)).ToString() );
}
for (int i = 0; i < 255; i++)
{
threads[i].Join();
}
}
Code:
IPScanner ip_scanner = new IPScanner();
ip_scanner.Scan();
But the following code works fine and returns in 10 seconds (this code is met often in google but applied not to sockets):
Code:
public class IPScanner
{
public IPScanner() { }
private void connect(object data)
{
Sleep(10000);
// Or do some math.
}
public void Scan()
{
Thread[] threads = new Thread[255];
for (int i = 0; i < 255; i++)
{
threads[i] = new Thread(new ParameterizedThreadStart(connect));
threads[i].Start( "xxx.xxx.xxx." + ((int)(i+1)).ToString() );
}
for (int i = 0; i < 255; i++)
{
threads[i].Join();
}
}
...
IPScanner ip_scanner = new IPScanner();
ip_scanner.Scan();
Thank you.