473,395 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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

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 :
Expand|Select|Wrap|Line Numbers
  1. public class PortScanner
  2. {
  3. private int m_iPort = 0;
  4. private bool m_bTimeOut = false;
  5. private string m_sStatus = "Not connected";
  6. private IPAddress m_oIPAddress;
  7. private AutoResetEvent m_oARSConnectDone = new AutoResetEvent(false);
  8.  
  9. public PortScanner(long iIP)
  10. {
  11. m_oIPAddress = new IPAddress(iIP);
  12. m_iPort = 80;
  13. }
  14. public int Port
  15. {
  16. get{ return m_iPort; }
  17. }
  18. public string IP
  19. {
  20. get{ return m_oIPAddress.ToString(); }
  21. }
  22. private void ConnectCallback(IAsyncResult ar)
  23. {
  24. if(m_bTimeOut)
  25. return;
  26.  
  27. Socket oSocket = (Socket)ar.AsyncState;
  28. try
  29. {
  30. // Complete the connection.
  31. oSocket.EndConnect(ar);
  32. m_sStatus = "Open";
  33. }
  34. catch
  35. {
  36. // The EndConnect method will throw a SocetException if the remote
  37. // host is reachable, but refuses connections on a port.
  38. m_sStatus = "Close";
  39. }
  40. finally
  41. {
  42. if (oSocket.Connected)
  43. oSocket.Shutdown(SocketShutdown.Both);
  44. oSocket.Close();
  45. oSocket=null;
  46. m_oARSConnectDone.Set(); //tell the main thread that the callback
  47. has been finished.
  48. Console.WriteLine(m_oIPAddress.ToString() + "--->" + m_sStatus);
  49. }
  50. }
  51.  
  52. // initiate a connection to the port.
  53. public void Scan()
  54. {
  55. try
  56. {
  57. m_bTimeOut = false;
  58. Socket oScanningIpPort = new Socket(AddressFamily.InterNetwork,
  59. SocketType.Stream, ProtocolType.Tcp);
  60. oScanningIpPort.BeginConnect(new IPEndPoint(m_oIPAddress, m_iPort),
  61. new AsyncCallback(ConnectCallback), oScanningIpPort);
  62. if(!m_oARSConnectDone.WaitOne(10000, true))
  63. {
  64. m_bTimeOut = true;
  65. oScanningIpPort.Close();
  66. oScanningIpPort = null;
  67. }
  68. m_oARSConnectDone.Close();
  69. }
  70. catch(SocketException ex)
  71. {
  72. Console.WriteLine(ex.ErrorCode);
  73. }
  74. }
  75. }
  76.  
  77.  
Main Code :
StartHTTPScanning -is called by a Form Button
Expand|Select|Wrap|Line Numbers
  1. private Thread m_oThreadScanning;
  2. private Queue m_queueIP = new Queue();
  3.  
  4. //flag to be used to tell the HTTP Scan Thread that IP is still
  5. enqueuing
  6. private bool m_bEnqueuingIP;
  7.  
  8. private int m_iMaxRunning = 10;
  9. //        private int m_iMaxRunning = 255;
  10.  
  11. // flag to be used to stop all running threads when user request to
  12. stop
  13. bool m_bRunning = true;
  14.  
  15. private void EnqueuingIP()
  16. {
  17. m_bEnqueuingIP = true;
  18. XmlDocument xDocLstIPs = new XmlDocument();
  19. xDocLstIPs.Load("IPRange.xml");
  20.  
  21. XmlNodeList xLstNdIPs = xDocLstIPs.SelectNodes("/RangeIPs/RangeIP");
  22. foreach(XmlElement xElemDomain in xLstNdIPs)
  23. {
  24. try
  25. {
  26. Int64 iStartIP =
  27. long.Parse(xElemDomain.GetAttribute("start").ToString());
  28. Int64 iEndIP =
  29. long.Parse(xElemDomain.GetAttribute("end").ToString());
  30. while(iStartIP <= iEndIP)
  31. {
  32. m_queueIP.Enqueue(iStartIP);
  33. iStartIP++;
  34. }
  35. }
  36. catch(Exception ex)
  37. {
  38. MessageBox.Show(ex.Message);
  39. }
  40. Thread.Sleep(2000);
  41. }
  42.  
  43. //end enqueuing
  44. m_bEnqueuingIP = false;
  45. }
  46.  
  47. public void HTTPScanRunFunction()
  48. {
  49. while(m_bRunning && (m_queueIP.Count 0 || m_bEnqueuingIP) &&
  50. int.Parse(Thread.CurrentThread.Name) < m_iMaxRunning)
  51. {
  52.  
  53. if(m_queueIP.Count == 0 && m_bEnqueuingIP)
  54. {
  55. Thread.Sleep(500);
  56. continue;
  57. }
  58. long iIP = 0;
  59. lock(m_queueIP)
  60. {
  61. iIP = Convert.ToInt64(m_queueIP.Dequeue());
  62. }
  63. if(iIP == 0)
  64. continue;
  65.  
  66. PortScanner oPortScanner =  new PortScanner(iIP);
  67.  
  68. // update thread information in the threads view list
  69. ListViewItem itemLog;
  70. itemLog =
  71. listViewThreads.Items[int.Parse(Thread.CurrentThread.Name)];
  72. itemLog.SubItems[0].Text = oPortScanner.IP.ToString();
  73. itemLog.SubItems[1].Text = oPortScanner.Port.ToString();
  74. itemLog.ImageIndex = 1;
  75. itemLog.BackColor = Color.WhiteSmoke;
  76.  
  77. // initialize status to Connect
  78. itemLog.SubItems[2].Text = "Scanning";
  79. itemLog.ForeColor = Color.Green;
  80.  
  81. oPortScanner.Scan();
  82.  
  83. if(m_bRunning == false)
  84. itemLog.SubItems[2].Text = "Stop";
  85.  
  86. itemLog.ImageIndex = 0;
  87. itemLog.SubItems[0].Text = "";
  88. itemLog.SubItems[1].Text = "";
  89. itemLog.SubItems[2].Text = "";
  90.  
  91. oPortScanner = null;
  92. }
  93.  
  94. }
  95.  
  96. private void HTTPScanning()
  97. {
  98. // start parsing thread
  99. Thread oThreadEnqueuingIP = new Thread(new ThreadStart(EnqueuingIP));
  100. oThreadEnqueuingIP.Name = "ThreadEnqueuingIP";
  101. oThreadEnqueuingIP.Start();
  102.  
  103. // create the threads
  104. Thread[] threadsRun = new Thread[ m_iMaxRunning ];
  105. int nIndex = 0;
  106. for(nIndex = 0; nIndex < m_iMaxRunning; nIndex ++)
  107. {
  108. // check if thread not created or not suspended
  109. if(threadsRun[nIndex] == null || threadsRun[nIndex].ThreadState !=
  110. ThreadState.Suspended)
  111. {
  112. threadsRun[nIndex] = new Thread( new ThreadStart(
  113. HTTPScanRunFunction ) );
  114.  
  115. // set thread name equal to its index
  116. threadsRun[nIndex].Name = nIndex.ToString();
  117.  
  118. lock(listViewThreads)
  119. {
  120. // add a new line in the view for the new thread
  121. ListViewItem item =
  122. listViewThreads.Items.Add(threadsRun[nIndex].Name, 0);
  123. string[] subItems = { "", "", "" };
  124. item.SubItems.AddRange(subItems);
  125. }
  126.  
  127. Thread.Sleep(200);
  128. // start the thread
  129. threadsRun[nIndex].Start();
  130.  
  131. }
  132. // check if the thread is suspended
  133. else if(threadsRun[nIndex].ThreadState == ThreadState.Suspended)
  134. {
  135. // resume the thread
  136. threadsRun[nIndex].Resume();
  137. }
  138. }
  139.  
  140. // wait for all of them to finish
  141. for ( nIndex = 0; nIndex < threadsRun.Length; nIndex ++ )
  142. threadsRun[nIndex].Join();
  143.  
  144.  
  145. this.toolBarButtonContinue.Enabled = true;
  146. this.toolBarButtonPause.Enabled = false;
  147. }
  148.  
  149. private void StartHTTPScanning()
  150. {
  151. // start parsing thread
  152. m_oThreadScanning = new Thread(new ThreadStart(HTTPScanning));
  153. m_oThreadScanning.Start();
  154. }
  155.  
Jan 24 '07 #1
2 4510
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/thread...threadpool.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" <jg******@yahoo.cawrote in message
news:11********************@v45g2000cwv.googlegrou ps.com...
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 :
Expand|Select|Wrap|Line Numbers
  1. public class PortScanner
  2. {
  3. private int m_iPort = 0;
  4. private bool m_bTimeOut = false;
  5. private string m_sStatus = "Not connected";
  6. private IPAddress m_oIPAddress;
  7. private AutoResetEvent m_oARSConnectDone = new AutoResetEvent(false);
  8. public PortScanner(long iIP)
  9. {
  10. m_oIPAddress = new IPAddress(iIP);
  11. m_iPort = 80;
  12. }
  13. public int Port
  14. {
  15. get{ return m_iPort; }
  16. }
  17. public string IP
  18. {
  19. get{ return m_oIPAddress.ToString(); }
  20. }
  21. private void ConnectCallback(IAsyncResult ar)
  22. {
  23. if(m_bTimeOut)
  24. return;
  25. Socket oSocket = (Socket)ar.AsyncState;
  26. try
  27. {
  28. // Complete the connection.
  29. oSocket.EndConnect(ar);
  30. m_sStatus = "Open";
  31. }
  32. catch
  33. {
  34. // The EndConnect method will throw a SocetException if the remote
  35. // host is reachable, but refuses connections on a port.
  36. m_sStatus = "Close";
  37. }
  38. finally
  39. {
  40. if (oSocket.Connected)
  41. oSocket.Shutdown(SocketShutdown.Both);
  42. oSocket.Close();
  43. oSocket=null;
  44. m_oARSConnectDone.Set(); //tell the main thread that the callback
  45. has been finished.
  46. Console.WriteLine(m_oIPAddress.ToString() + "--->" + m_sStatus);
  47. }
  48. }
  49. // initiate a connection to the port.
  50. public void Scan()
  51. {
  52. try
  53. {
  54. m_bTimeOut = false;
  55. Socket oScanningIpPort = new Socket(AddressFamily.InterNetwork,
  56. SocketType.Stream, ProtocolType.Tcp);
  57. oScanningIpPort.BeginConnect(new IPEndPoint(m_oIPAddress, m_iPort),
  58. new AsyncCallback(ConnectCallback), oScanningIpPort);
  59. if(!m_oARSConnectDone.WaitOne(10000, true))
  60. {
  61. m_bTimeOut = true;
  62. oScanningIpPort.Close();
  63. oScanningIpPort = null;
  64. }
  65. m_oARSConnectDone.Close();
  66. }
  67. catch(SocketException ex)
  68. {
  69. Console.WriteLine(ex.ErrorCode);
  70. }
  71. }
  72. }
  73.  
Main Code :
StartHTTPScanning -is called by a Form Button
Expand|Select|Wrap|Line Numbers
  1. private Thread m_oThreadScanning;
  2. private Queue m_queueIP = new Queue();
  3. //flag to be used to tell the HTTP Scan Thread that IP is still
  4. enqueuing
  5. private bool m_bEnqueuingIP;
  6. private int m_iMaxRunning = 10;
  7. // private int m_iMaxRunning = 255;
  8. // flag to be used to stop all running threads when user request to
  9. stop
  10. bool m_bRunning = true;
  11. private void EnqueuingIP()
  12. {
  13. m_bEnqueuingIP = true;
  14. XmlDocument xDocLstIPs = new XmlDocument();
  15. xDocLstIPs.Load("IPRange.xml");
  16. XmlNodeList xLstNdIPs = xDocLstIPs.SelectNodes("/RangeIPs/RangeIP");
  17. foreach(XmlElement xElemDomain in xLstNdIPs)
  18. {
  19. try
  20. {
  21. Int64 iStartIP =
  22. long.Parse(xElemDomain.GetAttribute("start").ToString());
  23. Int64 iEndIP =
  24. long.Parse(xElemDomain.GetAttribute("end").ToString());
  25. while(iStartIP <= iEndIP)
  26. {
  27. m_queueIP.Enqueue(iStartIP);
  28. iStartIP++;
  29. }
  30. }
  31. catch(Exception ex)
  32. {
  33. MessageBox.Show(ex.Message);
  34. }
  35. Thread.Sleep(2000);
  36. }
  37. //end enqueuing
  38. m_bEnqueuingIP = false;
  39. }
  40. public void HTTPScanRunFunction()
  41. {
  42. while(m_bRunning && (m_queueIP.Count 0 || m_bEnqueuingIP) &&
  43. int.Parse(Thread.CurrentThread.Name) < m_iMaxRunning)
  44. {
  45. if(m_queueIP.Count == 0 && m_bEnqueuingIP)
  46. {
  47. Thread.Sleep(500);
  48. continue;
  49. }
  50. long iIP = 0;
  51. lock(m_queueIP)
  52. {
  53. iIP = Convert.ToInt64(m_queueIP.Dequeue());
  54. }
  55. if(iIP == 0)
  56. continue;
  57. PortScanner oPortScanner =  new PortScanner(iIP);
  58. // update thread information in the threads view list
  59. ListViewItem itemLog;
  60. itemLog =
  61. listViewThreads.Items[int.Parse(Thread.CurrentThread.Name)];
  62. itemLog.SubItems[0].Text = oPortScanner.IP.ToString();
  63. itemLog.SubItems[1].Text = oPortScanner.Port.ToString();
  64. itemLog.ImageIndex = 1;
  65. itemLog.BackColor = Color.WhiteSmoke;
  66. // initialize status to Connect
  67. itemLog.SubItems[2].Text = "Scanning";
  68. itemLog.ForeColor = Color.Green;
  69. oPortScanner.Scan();
  70. if(m_bRunning == false)
  71. itemLog.SubItems[2].Text = "Stop";
  72. itemLog.ImageIndex = 0;
  73. itemLog.SubItems[0].Text = "";
  74. itemLog.SubItems[1].Text = "";
  75. itemLog.SubItems[2].Text = "";
  76. oPortScanner = null;
  77. }
  78. }
  79. private void HTTPScanning()
  80. {
  81. // start parsing thread
  82. Thread oThreadEnqueuingIP = new Thread(new ThreadStart(EnqueuingIP));
  83. oThreadEnqueuingIP.Name = "ThreadEnqueuingIP";
  84. oThreadEnqueuingIP.Start();
  85. // create the threads
  86. Thread[] threadsRun = new Thread[ m_iMaxRunning ];
  87. int nIndex = 0;
  88. for(nIndex = 0; nIndex < m_iMaxRunning; nIndex ++)
  89. {
  90. // check if thread not created or not suspended
  91. if(threadsRun[nIndex] == null || threadsRun[nIndex].ThreadState !=
  92. ThreadState.Suspended)
  93. {
  94. threadsRun[nIndex] = new Thread( new ThreadStart(
  95. HTTPScanRunFunction ) );
  96. // set thread name equal to its index
  97. threadsRun[nIndex].Name = nIndex.ToString();
  98. lock(listViewThreads)
  99. {
  100. // add a new line in the view for the new thread
  101. ListViewItem item =
  102. listViewThreads.Items.Add(threadsRun[nIndex].Name, 0);
  103. string[] subItems = { "", "", "" };
  104. item.SubItems.AddRange(subItems);
  105. }
  106. Thread.Sleep(200);
  107. // start the thread
  108. threadsRun[nIndex].Start();
  109. }
  110. // check if the thread is suspended
  111. else if(threadsRun[nIndex].ThreadState == ThreadState.Suspended)
  112. {
  113. // resume the thread
  114. threadsRun[nIndex].Resume();
  115. }
  116. }
  117. // wait for all of them to finish
  118. for ( nIndex = 0; nIndex < threadsRun.Length; nIndex ++ )
  119. threadsRun[nIndex].Join();
  120. this.toolBarButtonContinue.Enabled = true;
  121. this.toolBarButtonPause.Enabled = false;
  122. }
  123. private void StartHTTPScanning()
  124. {
  125. // start parsing thread
  126. m_oThreadScanning = new Thread(new ThreadStart(HTTPScanning));
  127. m_oThreadScanning.Start();
  128. }
  129.  

Jan 24 '07 #2
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......

On 24 jan, 16:31, "Robson Siqueira" <rob...@robsonfelix.comwrote:
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/thread...threadpool.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" <jgbid...@yahoo.cawrote in messagenews:11********************@v45g2000cwv.goo glegroups.com...
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 :
Expand|Select|Wrap|Line Numbers
  1.  public class PortScanner
  2.  {
  3.  private int m_iPort = 0;
  4.  private bool m_bTimeOut = false;
  5.  private string m_sStatus = "Not connected";
  6.  private IPAddress m_oIPAddress;
  7.  private AutoResetEvent m_oARSConnectDone = new AutoResetEvent(false);
Expand|Select|Wrap|Line Numbers
  1.         
  2.                  public PortScanner(long iIP)
  3.  {
  4.  m_oIPAddress = new IPAddress(iIP);
  5.  m_iPort = 80;
  6.  }
  7.  public int Port
  8.  {
  9.  get{ return m_iPort; }
  10.  }
  11.  public string IP
  12.  {
  13.  get{ return m_oIPAddress.ToString(); }
  14.  }
  15.  private void ConnectCallback(IAsyncResult ar)
  16.  {
  17.  if(m_bTimeOut)
  18.  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
    Expand|Select|Wrap|Line Numbers
    1.  private Thread m_oThreadScanning;
    2.  private Queue m_queueIP = new Queue();
    Expand|Select|Wrap|Line Numbers
    1.         
    2.                  //flag to be used to tell the HTTP Scan Thread that IP is still
    3.  enqueuing
    4.  private bool m_bEnqueuingIP;
    5.  
    6.         
    7.                  private int m_iMaxRunning = 10;
    8.  // private int m_iMaxRunning = 255;
    9.  
    10.         
    11.                  // flag to be used to stop all running threads when user request to
    12.  stop
    13.  bool m_bRunning = true;
    14.  
    15.         
    16.                  private void EnqueuingIP()
    17.  {
    18.  m_bEnqueuingIP = true;
    19.  XmlDocument xDocLstIPs = new XmlDocument();
    20.  xDocLstIPs.Load("IPRange.xml");
    21.  
    22.         
    23.                  XmlNodeList xLstNdIPs = xDocLstIPs.SelectNodes("/RangeIPs/RangeIP");
    24.  foreach(XmlElement xElemDomain in xLstNdIPs)
    25.  {
    26.  try
    27.  {
    28.  Int64 iStartIP =
    29.  long.Parse(xElemDomain.GetAttribute("start").ToString());
    30.  Int64 iEndIP =
    31.  long.Parse(xElemDomain.GetAttribute("end").ToString());
    32.  while(iStartIP <= iEndIP)
    33.  {
    34.  m_queueIP.Enqueue(iStartIP);
    35.  iStartIP++;
    36.  }
    37.  }
    38.  catch(Exception ex)
    39.  {
    40.  MessageBox.Show(ex.Message);
    41.  }
    42.  Thread.Sleep(2000);
    43.  }
    44.  
    45.         
    46.                  //end enqueuing
    47.  m_bEnqueuingIP = false;
    48.  }
    49.  
    50.         
    51.                  public void HTTPScanRunFunction()
    52.  {
    53.  while(m_bRunning && (m_queueIP.Count 0 || m_bEnqueuingIP) &&
    54.  int.Parse(Thread.CurrentThread.Name) < m_iMaxRunning)
    55.  {
    56.  
    57.         
    58.                  if(m_queueIP.Count == 0 && m_bEnqueuingIP)
    59.  {
    60.  Thread.Sleep(500);
    61.  continue;
    62.  }
    63.  long iIP = 0;
    64.  lock(m_queueIP)
    65.  {
    66.  iIP = Convert.ToInt64(m_queueIP.Dequeue());
    67.  }
    68.  if(iIP == 0)
    69.  continue;
    70.  
    71.         
    72.                  PortScanner oPortScanner =  new PortScanner(iIP);
    73.  
    74.         
    75.                  // update thread information in the threads view list
    76.  ListViewItem itemLog;
    77.  itemLog =
    78.  listViewThreads.Items[int.Parse(Thread.CurrentThread.Name)];
    79.  itemLog.SubItems[0].Text = oPortScanner.IP.ToString();
    80.  itemLog.SubItems[1].Text = oPortScanner.Port.ToString();
    81.  itemLog.ImageIndex = 1;
    82.  itemLog.BackColor = Color.WhiteSmoke;
    83.  
    84.         
    85.                  // initialize status to Connect
    86.  itemLog.SubItems[2].Text = "Scanning";
    87.  itemLog.ForeColor = Color.Green;
    88.  
    89.         
    90.                  oPortScanner.Scan();
    91.  
    92.         
    93.                  if(m_bRunning == false)
    94.  itemLog.SubItems[2].Text = "Stop";
    95.  
    96.         
    97.                  itemLog.ImageIndex = 0;
    98.  itemLog.SubItems[0].Text = "";
    99.  itemLog.SubItems[1].Text = "";
    100.  itemLog.SubItems[2].Text = "";
    101.  
    102.         
    103.                  oPortScanner = null;
    104.  }
    105.  
    106.         
    107.                  }
    108.  
    109.         
    110.                  private void HTTPScanning()
    111.  {
    112.  // start parsing thread
    113.  Thread oThreadEnqueuingIP = new Thread(new ThreadStart(EnqueuingIP));
    114.  oThreadEnqueuingIP.Name = "ThreadEnqueuingIP";
    115.  oThreadEnqueuingIP.Start();
    116.  
    117.         
    118.                  // create the threads
    119.  Thread[] threadsRun = new Thread[ m_iMaxRunning ];
    120.  int nIndex = 0;
    121.  for(nIndex = 0; nIndex < m_iMaxRunning; nIndex ++)
    122.  {
    123.  // check if thread not created or not suspended
    124.  if(threadsRun[nIndex] == null || threadsRun[nIndex].ThreadState !=
    125.  ThreadState.Suspended)
    126.  {
    127.  threadsRun[nIndex] = new Thread( new ThreadStart(
    128.  HTTPScanRunFunction ) );
    129.  
    130.         
    131.                  // set thread name equal to its index
    132.  threadsRun[nIndex].Name = nIndex.ToString();
    133.  
    134.         
    135.                  lock(listViewThreads)
    136.  {
    137.  // add a new line in the view for the new thread
    138.  ListViewItem item =
    139.  listViewThreads.Items.Add(threadsRun[nIndex].Name, 0);
    140.  string[] subItems = { "", "", "" };
    141.  item.SubItems.AddRange(subItems);
    142.  }
    143.  
    144.         
    145.                  Thread.Sleep(200);
    146.  // start the thread
    147.  threadsRun[nIndex].Start();
    148.  
    149.         
    150.                  }
    151.  // check if the thread is suspended
    152.  else if(threadsRun[nIndex].ThreadState == ThreadState.Suspended)
    153.  {
    154.  // resume the thread
    155.  threadsRun[nIndex].Resume();
    156.  }
    157.  }
    158.  
    159.         
    160.                  // wait for all of them to finish
    161.  for ( nIndex = 0; nIndex < threadsRun.Length; nIndex ++ )
    162.  threadsRun[nIndex].Join();
    163.  
    164.         
    165.                  this.toolBarButtonContinue.Enabled = true;
    166.  this.toolBarButtonPause.Enabled = false;
    167.  }
    168.  
    169.         
    170.                  private void StartHTTPScanning()
    171.  {
    172.  // start parsing thread
    173.  m_oThreadScanning = new Thread(new ThreadStart(HTTPScanning));
    174.  m_oThreadScanning.Start();
    175.  }
    176.  
    177.  
    - Masquer le texte des messages précédents -- Afficher le texte des messages précédents -
    Jan 25 '07 #3

    This thread has been closed and replies have been disabled. Please start a new discussion.

    Similar topics

    0
    by: Gonçalo Rodrigues | last post by:
    Hi, I have a problem with threads and sockets. I'll try to describe the problem in words with pseudo-code. I've been working on a few classes to make it easier to work with threads. This...
    3
    by: Sebastian Meyer | last post by:
    Hi Newsgroup, i have some problems with using threads and signals in one program. In my program i have three threads running, one for checking a directory at a specified interval to see if new...
    2
    by: Stephan Popp | last post by:
    Hi all, I've got a problem with stopping python-threads. I'm starting a thread with twisteds reactor.deferToThread which start a methodcall in a seperate thread. In this thread a swig-wrapped c++...
    3
    by: Manuel Hegemann | last post by:
    Hallo, in meinem Schulprojekt, soll eine Datei, jedesmal wenn Sie aktualisiert wird auf nen FTP-Server oder für den Test auf nen Netzwerkserver gespeichert werden. Das Problem ist, dass ich noch...
    4
    by: Nurchi BECHED | last post by:
    Hello, my dearest respected brother, All! I am writing an application which uses printer port to play with LEDs for now and something else later... I created a button which makes LEDs...
    0
    by: Mamatha | last post by:
    Hi I have application in VB.NET,In that application threads are created dynamically and displays URLs of a webpage in the listview.At the time of running each thread their URL values are stored...
    5
    by: Mr | last post by:
    Hi We have a application with Framework 1.1 and Vs .NET 2003. the application has a service with pooling; like a File system Watcher, but works. the system works fine in the development...
    2
    by: ThunderMusic | last post by:
    Hi, I have a class library with some classes... One of those classes fire events from a different thread. When I try to display the information contained in the event args of this event in my UI,...
    3
    by: _nabuchodonozor | last post by:
    Hi, its me again:P I'm writing my own mp3 player. I have loop which looks: while (trackBar1.Value != TrackLength) { TrackBar1.Value = TrackPosition(); } This loop set position to the...
    0
    by: Charles Arthur | last post by:
    How do i turn on java script on a villaon, callus and itel keypad mobile phone
    0
    by: ryjfgjl | last post by:
    If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
    0
    by: ryjfgjl | last post by:
    In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
    1
    by: nemocccc | last post by:
    hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
    1
    by: Sonnysonu | last post by:
    This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
    0
    by: Hystou | last post by:
    Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
    0
    Oralloy
    by: Oralloy | last post by:
    Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
    0
    jinu1996
    by: jinu1996 | last post by:
    In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
    0
    by: Hystou | last post by:
    Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

    By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

    To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.