Problem ... .Sockets and Threads (IP Scanning)

J

jgbid

Hi, I'm trying to build an IP Scanner inc c# for a specific port (80)
and for specific IP Ranges.

For example 24.36.148.1 to 24.36.148.255

My first step was to use TcpClient, but there are nothing to control
Timeout Connection... and I wasn't interested to wait 25-30sec for each
ip.

After some search, it's look like Socket was the solution with
BeginConnect. After a first look, I thought that all worked perfectly,
but after a second look... I noticed that after some scan... approx. 10
or 15, nothing work...
If I set maximum thread to 1, it works, this it what I got:
24.36.148.10--->Close
24.36.148.23--->Close
24.36.148.24--->Close
24.36.148.28--->Close
24.36.148.66--->Close
24.36.148.70--->Close
24.36.148.77--->Close
24.36.148.116--->Close
24.36.148.121--->Close
24.36.148.126--->Close
24.36.148.130--->Close
24.36.148.132--->Close
24.36.148.137--->Close
24.36.148.146--->Close
24.36.148.147--->Close
24.36.148.148--->Close
24.36.148.154--->Close
24.36.148.164--->Close
24.36.148.177--->Close
24.36.148.180--->Open
24.36.148.197--->Close
24.36.148.199--->Close
24.36.148.202--->Close
24.36.148.213--->Close
24.36.148.216--->Close
24.36.148.234--->Close
24.36.148.241--->Close
24.36.148.251--->Close

where the only one with Port 80 open is "24.36.148.180--->Open"
and where "Close" means "the remote host is reachable, but refuses
connections on a port"

If I set maximum Thread to 5 or something else better... the only thing
I got is :
24.36.148.10--->Close

Nothing else..... like if Socket doesn't work when they are too many
socket open...
But I tried by anything I know to kill the bad sockets

Here is my code :
PortScanner Class :
Code:
public class PortScanner
{
private int m_iPort = 0;
private bool m_bTimeOut = false;
private string m_sStatus = "Not connected";
private IPAddress m_oIPAddress;
private AutoResetEvent m_oARSConnectDone = new AutoResetEvent(false);

public PortScanner(long iIP)
{
m_oIPAddress = new IPAddress(iIP);
m_iPort = 80;
}
public int Port
{
get{ return m_iPort; }
}
public string IP
{
get{ return m_oIPAddress.ToString(); }
}
private void ConnectCallback(IAsyncResult ar)
{
if(m_bTimeOut)
return;

Socket oSocket = (Socket)ar.AsyncState;
try
{
// Complete the connection.
oSocket.EndConnect(ar);
m_sStatus = "Open";
}
catch
{
// The EndConnect method will throw a SocetException if the remote
// host is reachable, but refuses connections on a port.
m_sStatus = "Close";
}
finally
{
if (oSocket.Connected)
oSocket.Shutdown(SocketShutdown.Both);
oSocket.Close();
oSocket=null;
m_oARSConnectDone.Set(); //tell the main thread that the callback
has been finished.
Console.WriteLine(m_oIPAddress.ToString() + "--->" + m_sStatus);
}
}

// initiate a connection to the port.
public void Scan()
{
try
{
m_bTimeOut = false;
Socket oScanningIpPort = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
oScanningIpPort.BeginConnect(new IPEndPoint(m_oIPAddress, m_iPort),
new AsyncCallback(ConnectCallback), oScanningIpPort);
if(!m_oARSConnectDone.WaitOne(10000, true))
{
m_bTimeOut = true;
oScanningIpPort.Close();
oScanningIpPort = null;
}
m_oARSConnectDone.Close();
}
catch(SocketException ex)
{
Console.WriteLine(ex.ErrorCode);
}
}
}
Main Code :
StartHTTPScanning -> is called by a Form Button
Code:
private Thread m_oThreadScanning;
private Queue m_queueIP = new Queue();

//flag to be used to tell the HTTP Scan Thread that IP is still
enqueuing
private bool m_bEnqueuingIP;

private int m_iMaxRunning = 10;
//		private int m_iMaxRunning = 255;

// flag to be used to stop all running threads when user request to
stop
bool m_bRunning = true;

private void EnqueuingIP()
{
m_bEnqueuingIP = true;
XmlDocument xDocLstIPs = new XmlDocument();
xDocLstIPs.Load("IPRange.xml");

XmlNodeList xLstNdIPs = xDocLstIPs.SelectNodes("/RangeIPs/RangeIP");
foreach(XmlElement xElemDomain in xLstNdIPs)
{
try
{
Int64 iStartIP =
long.Parse(xElemDomain.GetAttribute("start").ToString());
Int64 iEndIP =
long.Parse(xElemDomain.GetAttribute("end").ToString());
while(iStartIP <= iEndIP)
{
m_queueIP.Enqueue(iStartIP);
iStartIP++;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Thread.Sleep(2000);
}

//end enqueuing
m_bEnqueuingIP = false;
}

public void HTTPScanRunFunction()
{
while(m_bRunning && (m_queueIP.Count > 0 || m_bEnqueuingIP) &&
int.Parse(Thread.CurrentThread.Name) < m_iMaxRunning)
{

if(m_queueIP.Count == 0 && m_bEnqueuingIP)
{
Thread.Sleep(500);
continue;
}
long iIP = 0;
lock(m_queueIP)
{
iIP = Convert.ToInt64(m_queueIP.Dequeue());
}
if(iIP == 0)
continue;

PortScanner oPortScanner =  new PortScanner(iIP);

// update thread information in the threads view list
ListViewItem itemLog;
itemLog =
listViewThreads.Items[int.Parse(Thread.CurrentThread.Name)];
itemLog.SubItems[0].Text = oPortScanner.IP.ToString();
itemLog.SubItems[1].Text = oPortScanner.Port.ToString();
itemLog.ImageIndex = 1;
itemLog.BackColor = Color.WhiteSmoke;

// initialize status to Connect
itemLog.SubItems[2].Text = "Scanning";
itemLog.ForeColor = Color.Green;

oPortScanner.Scan();

if(m_bRunning == false)
itemLog.SubItems[2].Text = "Stop";

itemLog.ImageIndex = 0;
itemLog.SubItems[0].Text = "";
itemLog.SubItems[1].Text = "";
itemLog.SubItems[2].Text = "";

oPortScanner = null;
}

}

private void HTTPScanning()
{
// start parsing thread
Thread oThreadEnqueuingIP = new Thread(new ThreadStart(EnqueuingIP));
oThreadEnqueuingIP.Name = "ThreadEnqueuingIP";
oThreadEnqueuingIP.Start();

// create the threads
Thread[] threadsRun = new Thread[ m_iMaxRunning ];
int nIndex = 0;
for(nIndex = 0; nIndex < m_iMaxRunning; nIndex ++)
{
// check if thread not created or not suspended
if(threadsRun[nIndex] == null || threadsRun[nIndex].ThreadState !=
ThreadState.Suspended)
{
threadsRun[nIndex] = new Thread( new ThreadStart(
HTTPScanRunFunction ) );

// set thread name equal to its index
threadsRun[nIndex].Name = nIndex.ToString();

lock(listViewThreads)
{
// add a new line in the view for the new thread
ListViewItem item =
listViewThreads.Items.Add(threadsRun[nIndex].Name, 0);
string[] subItems = { "", "", "" };
item.SubItems.AddRange(subItems);
}

Thread.Sleep(200);
// start the thread
threadsRun[nIndex].Start();

}
// check if the thread is suspended
else if(threadsRun[nIndex].ThreadState == ThreadState.Suspended)
{
// resume the thread
threadsRun[nIndex].Resume();
}
}

// wait for all of them to finish
for ( nIndex = 0; nIndex < threadsRun.Length; nIndex ++ )
threadsRun[nIndex].Join();


this.toolBarButtonContinue.Enabled = true;
this.toolBarButtonPause.Enabled = false;
}

private void StartHTTPScanning()
{
// start parsing thread
m_oThreadScanning = new Thread(new ThreadStart(HTTPScanning));
m_oThreadScanning.Start();
}
 
R

Robson Siqueira

jgbid,

It looks to me that:

a) your thread control stuff looks kinda hard to maintain for me, besides
that it is my best shot for the code you sent. If you have just one thread
working, it means that you are not multi threading at all. Why don't you
take a look on this framework:
http://www.codeproject.com/cs/threads/smartthreadpool.asp. I've used this
for quite some time and it has saved my life.
b) on the worker thread, instead of using asynchronous calls, use
synchronous. I am pretty sure it will be easier to maintain and to test.

I hope it helps!
--
Regards,
Robson Siqueira
Enterprise Architect
jgbid said:
Hi, I'm trying to build an IP Scanner inc c# for a specific port (80)
and for specific IP Ranges.

For example 24.36.148.1 to 24.36.148.255

My first step was to use TcpClient, but there are nothing to control
Timeout Connection... and I wasn't interested to wait 25-30sec for each
ip.

After some search, it's look like Socket was the solution with
BeginConnect. After a first look, I thought that all worked perfectly,
but after a second look... I noticed that after some scan... approx. 10
or 15, nothing work...
If I set maximum thread to 1, it works, this it what I got:
24.36.148.10--->Close
24.36.148.23--->Close
24.36.148.24--->Close
24.36.148.28--->Close
24.36.148.66--->Close
24.36.148.70--->Close
24.36.148.77--->Close
24.36.148.116--->Close
24.36.148.121--->Close
24.36.148.126--->Close
24.36.148.130--->Close
24.36.148.132--->Close
24.36.148.137--->Close
24.36.148.146--->Close
24.36.148.147--->Close
24.36.148.148--->Close
24.36.148.154--->Close
24.36.148.164--->Close
24.36.148.177--->Close
24.36.148.180--->Open
24.36.148.197--->Close
24.36.148.199--->Close
24.36.148.202--->Close
24.36.148.213--->Close
24.36.148.216--->Close
24.36.148.234--->Close
24.36.148.241--->Close
24.36.148.251--->Close

where the only one with Port 80 open is "24.36.148.180--->Open"
and where "Close" means "the remote host is reachable, but refuses
connections on a port"

If I set maximum Thread to 5 or something else better... the only thing
I got is :
24.36.148.10--->Close

Nothing else..... like if Socket doesn't work when they are too many
socket open...
But I tried by anything I know to kill the bad sockets

Here is my code :
PortScanner Class :
Code:
public class PortScanner
{
private int m_iPort = 0;
private bool m_bTimeOut = false;
private string m_sStatus = "Not connected";
private IPAddress m_oIPAddress;
private AutoResetEvent m_oARSConnectDone = new AutoResetEvent(false);

public PortScanner(long iIP)
{
m_oIPAddress = new IPAddress(iIP);
m_iPort = 80;
}
public int Port
{
get{ return m_iPort; }
}
public string IP
{
get{ return m_oIPAddress.ToString(); }
}
private void ConnectCallback(IAsyncResult ar)
{
if(m_bTimeOut)
return;

Socket oSocket = (Socket)ar.AsyncState;
try
{
// Complete the connection.
oSocket.EndConnect(ar);
m_sStatus = "Open";
}
catch
{
// The EndConnect method will throw a SocetException if the remote
// host is reachable, but refuses connections on a port.
m_sStatus = "Close";
}
finally
{
if (oSocket.Connected)
oSocket.Shutdown(SocketShutdown.Both);
oSocket.Close();
oSocket=null;
m_oARSConnectDone.Set(); //tell the main thread that the callback
has been finished.
Console.WriteLine(m_oIPAddress.ToString() + "--->" + m_sStatus);
}
}

// initiate a connection to the port.
public void Scan()
{
try
{
m_bTimeOut = false;
Socket oScanningIpPort = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
oScanningIpPort.BeginConnect(new IPEndPoint(m_oIPAddress, m_iPort),
new AsyncCallback(ConnectCallback), oScanningIpPort);
if(!m_oARSConnectDone.WaitOne(10000, true))
{
m_bTimeOut = true;
oScanningIpPort.Close();
oScanningIpPort = null;
}
m_oARSConnectDone.Close();
}
catch(SocketException ex)
{
Console.WriteLine(ex.ErrorCode);
}
}
}
Main Code :
StartHTTPScanning -> is called by a Form Button
Code:
private Thread m_oThreadScanning;
private Queue m_queueIP = new Queue();

//flag to be used to tell the HTTP Scan Thread that IP is still
enqueuing
private bool m_bEnqueuingIP;

private int m_iMaxRunning = 10;
// private int m_iMaxRunning = 255;

// flag to be used to stop all running threads when user request to
stop
bool m_bRunning = true;

private void EnqueuingIP()
{
m_bEnqueuingIP = true;
XmlDocument xDocLstIPs = new XmlDocument();
xDocLstIPs.Load("IPRange.xml");

XmlNodeList xLstNdIPs = xDocLstIPs.SelectNodes("/RangeIPs/RangeIP");
foreach(XmlElement xElemDomain in xLstNdIPs)
{
try
{
Int64 iStartIP =
long.Parse(xElemDomain.GetAttribute("start").ToString());
Int64 iEndIP =
long.Parse(xElemDomain.GetAttribute("end").ToString());
while(iStartIP <= iEndIP)
{
m_queueIP.Enqueue(iStartIP);
iStartIP++;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Thread.Sleep(2000);
}

//end enqueuing
m_bEnqueuingIP = false;
}

public void HTTPScanRunFunction()
{
while(m_bRunning && (m_queueIP.Count > 0 || m_bEnqueuingIP) &&
int.Parse(Thread.CurrentThread.Name) < m_iMaxRunning)
{

if(m_queueIP.Count == 0 && m_bEnqueuingIP)
{
Thread.Sleep(500);
continue;
}
long iIP = 0;
lock(m_queueIP)
{
iIP = Convert.ToInt64(m_queueIP.Dequeue());
}
if(iIP == 0)
continue;

PortScanner oPortScanner =  new PortScanner(iIP);

// update thread information in the threads view list
ListViewItem itemLog;
itemLog =
listViewThreads.Items[int.Parse(Thread.CurrentThread.Name)];
itemLog.SubItems[0].Text = oPortScanner.IP.ToString();
itemLog.SubItems[1].Text = oPortScanner.Port.ToString();
itemLog.ImageIndex = 1;
itemLog.BackColor = Color.WhiteSmoke;

// initialize status to Connect
itemLog.SubItems[2].Text = "Scanning";
itemLog.ForeColor = Color.Green;

oPortScanner.Scan();

if(m_bRunning == false)
itemLog.SubItems[2].Text = "Stop";

itemLog.ImageIndex = 0;
itemLog.SubItems[0].Text = "";
itemLog.SubItems[1].Text = "";
itemLog.SubItems[2].Text = "";

oPortScanner = null;
}

}

private void HTTPScanning()
{
// start parsing thread
Thread oThreadEnqueuingIP = new Thread(new ThreadStart(EnqueuingIP));
oThreadEnqueuingIP.Name = "ThreadEnqueuingIP";
oThreadEnqueuingIP.Start();

// create the threads
Thread[] threadsRun = new Thread[ m_iMaxRunning ];
int nIndex = 0;
for(nIndex = 0; nIndex < m_iMaxRunning; nIndex ++)
{
// check if thread not created or not suspended
if(threadsRun[nIndex] == null || threadsRun[nIndex].ThreadState !=
ThreadState.Suspended)
{
threadsRun[nIndex] = new Thread( new ThreadStart(
HTTPScanRunFunction ) );

// set thread name equal to its index
threadsRun[nIndex].Name = nIndex.ToString();

lock(listViewThreads)
{
// add a new line in the view for the new thread
ListViewItem item =
listViewThreads.Items.Add(threadsRun[nIndex].Name, 0);
string[] subItems = { "", "", "" };
item.SubItems.AddRange(subItems);
}

Thread.Sleep(200);
// start the thread
threadsRun[nIndex].Start();

}
// check if the thread is suspended
else if(threadsRun[nIndex].ThreadState == ThreadState.Suspended)
{
// resume the thread
threadsRun[nIndex].Resume();
}
}

// wait for all of them to finish
for ( nIndex = 0; nIndex < threadsRun.Length; nIndex ++ )
threadsRun[nIndex].Join();


this.toolBarButtonContinue.Enabled = true;
this.toolBarButtonPause.Enabled = false;
}

private void StartHTTPScanning()
{
// start parsing thread
m_oThreadScanning = new Thread(new ThreadStart(HTTPScanning));
m_oThreadScanning.Start();
}
 
J

jgbid

Hi Robson, thanks to trying to help me... I tried the script you told
me, but I have the same problem with "normal thread".. even if I kill
it(i tried anything I could to kill it... shutdown, close, dispose,
null, etc.), the Thread CallBack function is executed at the end even
if I set a Wait Delay to 0 sec.

I mean :
If I create a Thread with your framework (or with a normal thread) and
I set the timeout of this thread to 5sec.
When it is created, the callback function is called.
In this function, there are a synchronous Socket Connection with
TcpClient on a inactive host. (TcpClient.Connect)
After 5sec, the main thread is terminated, I shutdown it, but the
thread is still active.. after 25sec, TcpClient.Connect has a timeout
(SocketException).. and I catch an error in the callBack function..
What I want to do... is stop the thread and the callback function,
because I want to loop over thousound of IP Address.. so I can't just
wait 25sec for each ip...
It's why I'd like to have about 50 threads for each to scan an IP...
but with a timeout of 5sec (instead of 25sec)
this is the example for 15 threads.... what I don't understand is that
the first 10 is about 5sec ... but the others are 30sec and more....

They are 15 threads calling Scan2 until the IP Queue is empty
public void Scan2()
{
TcpClient oScanningIpPort = new TcpClient();
SmartThreadPool smartThreadPool = new SmartThreadPool();
smartThreadPool.Name = m_oIPAddress.ToString();

IWorkItemResult wir = smartThreadPool.QueueWorkItem(new
WorkItemCallback(this.DoRealWork), oScanningIpPort);
smartThreadPool.WaitForIdle(5000);

smartThreadPool.Shutdown();
smartThreadPool.Cancel();
smartThreadPool.Dispose();
oScanningIpPort.Close();
oScanningIpPort = null;
}
private object DoRealWork(object state)
{
TcpClient oScanningIpPort = (TcpClient) state;
DateTime dtNow = DateTime.Now;
try
{
oScanningIpPort.Connect(m_oIPAddress, m_iPort);
m_sStatus = "Open";
}
catch
{
m_sStatus = "Close";
// Console.WriteLine(m_oIPAddress.ToString() + "=" + m_sStatus);
}
finally
{
Console.WriteLine(m_oIPAddress.ToString() + "=" + m_sStatus + " -->
Time : " + Convert.ToString(DateTime.Now - dtNow));
}
return m_sStatus;
}

Thats what I got in the console screen
N.B ----> The time at end it's the time execution between the Connect
Call and The End of the call...
The first 12 works within 5 secs... and look at the others

The thread 'STP 24.36.148.1 Thread #0' (0x1c4c) has exited with code 0
(0x0).
The thread 'STP 24.36.148.2 Thread #0' (0xbd4) has exited with code 0
(0x0).
The thread 'STP 24.36.148.3 Thread #0' (0x1a24) has exited with code 0
(0x0).
24.36.148.1=Close --> Time : 00:00:05.4062500
24.36.148.2=Close --> Time : 00:00:05.2343750
24.36.148.3=Close --> Time : 00:00:05.0468750
The thread 'STP 24.36.148.4 Thread #0' (0x1464) has exited with code 0
(0x0).
24.36.148.4=Close --> Time : 00:00:05
The thread 'STP 24.36.148.5 Thread #0' (0x194) has exited with code 0
(0x0).
24.36.148.5=Close --> Time : 00:00:05
The thread 'STP 24.36.148.6 Thread #0' (0x1c68) has exited with code 0
(0x0).
24.36.148.6=Close --> Time : 00:00:05
The thread 'STP 24.36.148.7 Thread #0' (0x1988) has exited with code 0
(0x0).
24.36.148.7=Close --> Time : 00:00:05
The thread 'STP 24.36.148.8 Thread #0' (0x24cc) has exited with code 0
(0x0).
24.36.148.8=Close --> Time : 00:00:05
The thread 'STP 24.36.148.9 Thread #0' (0x106c) has exited with code 0
(0x0).
24.36.148.9=Close --> Time : 00:00:05
The thread 'STP 24.36.148.11 Thread #0' (0xd80) has exited with code 0
(0x0).
24.36.148.11=Close --> Time : 00:00:05
The thread 'STP 24.36.148.13 Thread #0' (0xd34) has exited with code 0
(0x0).
24.36.148.13=Close --> Time : 00:00:14.0156250
24.36.148.12=Close --> Time : 00:00:34.0625000
24.36.148.14=Close --> Time : 00:00:33.6562500
24.36.148.15=Close --> Time : 00:00:33.4531250
The thread 'STP 24.36.148.12 Thread #0' (0x1724) has exited with code 0
(0x0).
The thread 'STP 24.36.148.14 Thread #0' (0xbec) has exited with code 0
(0x0).
The thread 'STP 24.36.148.15 Thread #0' (0x19f8) has exited with code 0
(0x0).
24.36.148.17=Close --> Time : 00:00:31.3281250
24.36.148.16=Close --> Time : 00:00:31.3593750
24.36.148.18=Close --> Time : 00:00:31.3281250
The thread 'STP 24.36.148.16 Thread #0' (0x1344) has exited with code 0
(0x0).
The thread 'STP 24.36.148.17 Thread #0' (0xb5c) has exited with code 0
(0x0).
The thread 'STP 24.36.148.18 Thread #0' (0x14a4) has exited with code 0
(0x0).
24.36.148.19=Close --> Time : 00:00:31.8125000
24.36.148.20=Close --> Time : 00:00:31.6562500
24.36.148.21=Close --> Time : 00:00:31.4531250
The thread 'STP 24.36.148.19 Thread #0' (0xac4) has exited with code 0
(0x0).
The thread 'STP 24.36.148.20 Thread #0' (0x2510) has exited with code 0
(0x0).
The thread 'STP 24.36.148.21 Thread #0' (0xd14) has exited with code 0
(0x0).
The thread 'STP 24.36.148.23 Thread #0' (0x850) has exited with code 0
(0x0).
The thread 'STP 24.36.148.24 Thread #0' (0x13d4) has exited with code 0
(0x0).
24.36.148.23=Close --> Time : 00:00:31.1250000
24.36.148.24=Close --> Time : 00:00:30.9375000
The thread 'STP 24.36.148.22 Thread #0' (0x1f2c) has exited with code 0
(0x0).
24.36.148.22=Close --> Time : 00:00:31.7500000
The thread 'STP 24.36.148.28 Thread #0' (0x900) has exited with code 0
(0x0).
24.36.148.28=Close --> Time : 00:00:30.4375000
The thread 'STP 24.36.148.25 Thread #0' (0x1248) has exited with code 0
(0x0).
24.36.148.25=Close --> Time : 00:00:50.6562500
The thread 'STP 24.36.148.27 Thread #0' (0x1674) has exited with code 0
(0x0).
The thread 'STP 24.36.148.26 Thread #0' (0x21ec) has exited with code 0
(0x0).
24.36.148.27=Close --> Time : 00:00:50.5781250
24.36.148.26=Close --> Time : 00:00:50.7656250
24.36.148.30=Close --> Time : 00:00:50.4843750
24.36.148.31=Close --> Time : 00:00:47.8906250
24.36.148.29=Close --> Time : 00:00:50.6875000
24.36.148.32=Close --> Time : 00:00:47.8906250
The thread 'STP 24.36.148.29 Thread #0' (0x1878) has exited with code 0
(0x0).
The thread 'STP 24.36.148.31 Thread #0' (0x1c40) has exited with code 0
(0x0).
The thread 'STP 24.36.148.30 Thread #0' (0xcc8) has exited with code 0
(0x0).
The thread 'STP 24.36.148.32 Thread #0' (0x1d94) has exited with code 0
(0x0).
The thread 'STP 24.36.148.33 Thread #0' (0xdd0) has exited with code 0
(0x0).
24.36.148.33=Close --> Time : 00:00:47.9062500

........................

The thread 'STP 24.36.148.44 Thread #0' (0x19dc) has exited with code 0
(0x0).
The thread 'STP 24.36.148.45 Thread #0' (0x205c) has exited with code 0
(0x0).
24.36.148.45=Close --> Time : 00:01:07.0937500
The thread '1' (0x1b78) has exited with code 0 (0x0).
The thread '0' (0x1a20) has exited with code 0 (0x0).
The thread '2' (0x10f0) has exited with code 0 (0x0).
The thread '9' (0x158c) has exited with code 0 (0x0).
The thread '3' (0x2450) has exited with code 0 (0x0).
The thread '4' (0x1458) has exited with code 0 (0x0).
The thread '5' (0x380) has exited with code 0 (0x0).
The thread '6' (0x234c) has exited with code 0 (0x0).
The thread '7' (0xc70) has exited with code 0 (0x0).
The thread '8' (0x94) has exited with code 0 (0x0).
The thread '10' (0x1da0) has exited with code 0 (0x0).
The thread '11' (0xfe0) has exited with code 0 (0x0).
The thread '12' (0xa08) has exited with code 0 (0x0).
The thread '13' (0x229c) has exited with code 0 (0x0).
The thread '14' (0x16ec) has exited with code 0 (0x0).
The thread '<No Name>' (0x231c) has exited with code 0 (0x0).
The thread 'STP 24.36.148.46 Thread #0' (0x4dc) has exited with code 0
(0x0).
24.36.148.46=Close --> Time : 00:01:23.9218750
The thread 'STP 24.36.148.47 Thread #0' (0x35c) has exited with code 0
(0x0).
24.36.148.47=Close --> Time : 00:01:24.4062500
The thread 'STP 24.36.148.48 Thread #0' (0xe30) has exited with code 0
(0x0).
24.36.148.48=Close --> Time : 00:01:24.5000000
24.36.148.51=Close --> Time : 00:01:24.5312500
24.36.148.49=Close --> Time : 00:01:24.8906250
24.36.148.50=Close --> Time : 00:01:24.7343750
The thread 'STP 24.36.148.49 Thread #0' (0x15cc) has exited with code 0
(0x0).
The thread 'STP 24.36.148.50 Thread #0' (0xa48) has exited with code 0
(0x0).
The thread 'STP 24.36.148.52 Thread #0' (0x7c0) has exited with code 0
(0x0).
The thread 'STP 24.36.148.51 Thread #0' (0x1294) has exited with code 0
(0x0).
The thread 'STP 24.36.148.53 Thread #0' (0x8c8) has exited with code 0
(0x0).
24.36.148.52=Close --> Time : 00:01:24.3437500
24.36.148.53=Close --> Time : 00:01:24.1875000

..........

The thread 'STP 24.36.148.209 Thread #0' (0x1084) has exited with code
0 (0x0).
24.36.148.209=Close --> Time : 00:05:29.4218750
The thread 'STP 24.36.148.210 Thread #0' (0x9a4) has exited with code 0
(0x0).
24.36.148.210=Close --> Time : 00:05:29.4218750
The thread 'STP 24.36.148.211 Thread #0' (0x558) has exited with code 0
(0x0).
24.36.148.211=Close --> Time : 00:05:28.0937500

.............

24.36.148.253=Close --> Time : 00:06:38.6093750
The thread 'STP 24.36.148.254 Thread #0' (0x1f00) has exited with code
0 (0x0).
24.36.148.254=Close --> Time : 00:06:38.7187500
The thread 'STP 24.36.148.255 Thread #0' (0x1a5c) has exited with code
0 (0x0).
24.36.148.255=Close --> Time : 00:06:38.6093750

I don't undertand......

jgbid,

It looks to me that:

a) your thread control stuff looks kinda hard to maintain for me, besides
that it is my best shot for the code you sent. If you have just one thread
working, it means that you are not multi threading at all. Why don't you
take a look on this framework:http://www.codeproject.com/cs/threads/smartthreadpool.asp. I've used this
for quite some time and it has saved my life.
b) on the worker thread, instead of using asynchronous calls, use
synchronous. I am pretty sure it will be easier to maintain and to test.

I hope it helps!
--
Regards,
Robson Siqueira


Hi, I'm trying to build an IP Scanner inc c# for a specific port (80)
and for specific IP Ranges.
For example 24.36.148.1 to 24.36.148.255
My first step was to use TcpClient, but there are nothing to control
Timeout Connection... and I wasn't interested to wait 25-30sec for each
ip.
After some search, it's look like Socket was the solution with
BeginConnect. After a first look, I thought that all worked perfectly,
but after a second look... I noticed that after some scan... approx. 10
or 15, nothing work...
If I set maximum thread to 1, it works, this it what I got:
24.36.148.10--->Close
24.36.148.23--->Close
24.36.148.24--->Close
24.36.148.28--->Close
24.36.148.66--->Close
24.36.148.70--->Close
24.36.148.77--->Close
24.36.148.116--->Close
24.36.148.121--->Close
24.36.148.126--->Close
24.36.148.130--->Close
24.36.148.132--->Close
24.36.148.137--->Close
24.36.148.146--->Close
24.36.148.147--->Close
24.36.148.148--->Close
24.36.148.154--->Close
24.36.148.164--->Close
24.36.148.177--->Close
24.36.148.180--->Open
24.36.148.197--->Close
24.36.148.199--->Close
24.36.148.202--->Close
24.36.148.213--->Close
24.36.148.216--->Close
24.36.148.234--->Close
24.36.148.241--->Close
24.36.148.251--->Close
where the only one with Port 80 open is "24.36.148.180--->Open"
and where "Close" means "the remote host is reachable, but refuses
connections on a port"
If I set maximum Thread to 5 or something else better... the only thing
I got is :
24.36.148.10--->Close
Nothing else..... like if Socket doesn't work when they are too many
socket open...
But I tried by anything I know to kill the bad sockets
Here is my code :
PortScanner Class :
Code:
public class PortScanner
{
private int m_iPort = 0;
private bool m_bTimeOut = false;
private string m_sStatus = "Not connected";
private IPAddress m_oIPAddress;
private AutoResetEvent m_oARSConnectDone = new AutoResetEvent(false);[/QUOTE]
[QUOTE]
public PortScanner(long iIP)
{
m_oIPAddress = new IPAddress(iIP);
m_iPort = 80;
}
public int Port
{
get{ return m_iPort; }
}
public string IP
{
get{ return m_oIPAddress.ToString(); }
}
private void ConnectCallback(IAsyncResult ar)
{
if(m_bTimeOut)
return;[/QUOTE]
[QUOTE]
Socket oSocket = (Socket)ar.AsyncState;
try
{
// Complete the connection.
oSocket.EndConnect(ar);
m_sStatus = "Open";
}
catch
{
// The EndConnect method will throw a SocetException if the remote
// host is reachable, but refuses connections on a port.
m_sStatus = "Close";
}
finally
{
if (oSocket.Connected)
oSocket.Shutdown(SocketShutdown.Both);
oSocket.Close();
oSocket=null;
m_oARSConnectDone.Set(); //tell the main thread that the callback
has been finished.
Console.WriteLine(m_oIPAddress.ToString() + "--->" + m_sStatus);
}
}[/QUOTE]
[QUOTE]
// initiate a connection to the port.
public void Scan()
{
try
{
m_bTimeOut = false;
Socket oScanningIpPort = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
oScanningIpPort.BeginConnect(new IPEndPoint(m_oIPAddress, m_iPort),
new AsyncCallback(ConnectCallback), oScanningIpPort);
if(!m_oARSConnectDone.WaitOne(10000, true))
{
m_bTimeOut = true;
oScanningIpPort.Close();
oScanningIpPort = null;
}
m_oARSConnectDone.Close();
}
catch(SocketException ex)
{
Console.WriteLine(ex.ErrorCode);
}
}
}[/QUOTE]
[QUOTE]
Main Code :
StartHTTPScanning -> is called by a Form Button
Code:
private Thread m_oThreadScanning;
private Queue m_queueIP = new Queue();[/QUOTE]
[QUOTE]
//flag to be used to tell the HTTP Scan Thread that IP is still
enqueuing
private bool m_bEnqueuingIP;[/QUOTE]
[QUOTE]
private int m_iMaxRunning = 10;
// private int m_iMaxRunning = 255;[/QUOTE]
[QUOTE]
// flag to be used to stop all running threads when user request to
stop
bool m_bRunning = true;[/QUOTE]
[QUOTE]
private void EnqueuingIP()
{
m_bEnqueuingIP = true;
XmlDocument xDocLstIPs = new XmlDocument();
xDocLstIPs.Load("IPRange.xml");[/QUOTE]
[QUOTE]
XmlNodeList xLstNdIPs = xDocLstIPs.SelectNodes("/RangeIPs/RangeIP");
foreach(XmlElement xElemDomain in xLstNdIPs)
{
try
{
Int64 iStartIP =
long.Parse(xElemDomain.GetAttribute("start").ToString());
Int64 iEndIP =
long.Parse(xElemDomain.GetAttribute("end").ToString());
while(iStartIP <= iEndIP)
{
m_queueIP.Enqueue(iStartIP);
iStartIP++;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Thread.Sleep(2000);
}[/QUOTE]
[QUOTE]
//end enqueuing
m_bEnqueuingIP = false;
}[/QUOTE]
[QUOTE]
public void HTTPScanRunFunction()
{
while(m_bRunning && (m_queueIP.Count > 0 || m_bEnqueuingIP) &&
int.Parse(Thread.CurrentThread.Name) < m_iMaxRunning)
{[/QUOTE]
[QUOTE]
if(m_queueIP.Count == 0 && m_bEnqueuingIP)
{
Thread.Sleep(500);
continue;
}
long iIP = 0;
lock(m_queueIP)
{
iIP = Convert.ToInt64(m_queueIP.Dequeue());
}
if(iIP == 0)
continue;[/QUOTE]
[QUOTE]
PortScanner oPortScanner =  new PortScanner(iIP);[/QUOTE]
[QUOTE]
// update thread information in the threads view list
ListViewItem itemLog;
itemLog =
listViewThreads.Items[int.Parse(Thread.CurrentThread.Name)];
itemLog.SubItems[0].Text = oPortScanner.IP.ToString();
itemLog.SubItems[1].Text = oPortScanner.Port.ToString();
itemLog.ImageIndex = 1;
itemLog.BackColor = Color.WhiteSmoke;[/QUOTE]
[QUOTE]
// initialize status to Connect
itemLog.SubItems[2].Text = "Scanning";
itemLog.ForeColor = Color.Green; [QUOTE]
oPortScanner.Scan();[/QUOTE]

if(m_bRunning == false)
itemLog.SubItems[2].Text = "Stop";[/QUOTE]
[QUOTE]
itemLog.ImageIndex = 0;
itemLog.SubItems[0].Text = "";
itemLog.SubItems[1].Text = "";
itemLog.SubItems[2].Text = "";[/QUOTE]
[QUOTE]
oPortScanner = null;
} 

private void HTTPScanning()
{
// start parsing thread
Thread oThreadEnqueuingIP = new Thread(new ThreadStart(EnqueuingIP));
oThreadEnqueuingIP.Name = "ThreadEnqueuingIP";
oThreadEnqueuingIP.Start();[/QUOTE]
[QUOTE]
// create the threads
Thread[] threadsRun = new Thread[ m_iMaxRunning ];
int nIndex = 0;
for(nIndex = 0; nIndex < m_iMaxRunning; nIndex ++)
{
// check if thread not created or not suspended
if(threadsRun[nIndex] == null || threadsRun[nIndex].ThreadState !=
ThreadState.Suspended)
{
threadsRun[nIndex] = new Thread( new ThreadStart(
HTTPScanRunFunction ) );[/QUOTE]
[QUOTE]
// set thread name equal to its index
threadsRun[nIndex].Name = nIndex.ToString();[/QUOTE]
[QUOTE]
lock(listViewThreads)
{
// add a new line in the view for the new thread
ListViewItem item =
listViewThreads.Items.Add(threadsRun[nIndex].Name, 0);
string[] subItems = { "", "", "" };
item.SubItems.AddRange(subItems);
}[/QUOTE]
[QUOTE]
Thread.Sleep(200);
// start the thread
threadsRun[nIndex].Start();[/QUOTE]
[QUOTE]
}
// check if the thread is suspended
else if(threadsRun[nIndex].ThreadState == ThreadState.Suspended)
{
// resume the thread
threadsRun[nIndex].Resume();
}
}[/QUOTE]
[QUOTE]
// wait for all of them to finish
for ( nIndex = 0; nIndex < threadsRun.Length; nIndex ++ )
threadsRun[nIndex].Join();[/QUOTE]
[QUOTE]
this.toolBarButtonContinue.Enabled = true;
this.toolBarButtonPause.Enabled = false;
}[/QUOTE]
[QUOTE]
private void StartHTTPScanning()
{
// start parsing thread
m_oThreadScanning = new Thread(new ThreadStart(HTTPScanning));
m_oThreadScanning.Start();
}
- Masquer le texte des messages précédents -- Afficher le texte des messages précédents -
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top