0

I' m trying to do a simple tcp port scan using socket connect, and I m using a thread pool, but I don't get the output that I expect, the code for the thread pool is from here.

My code:

IPAddress dstIpAddress ; IPAddress.TryParse("192.168.2.106", out dstIpAddress); Action<IPAddress,int> tcpConnect = (( dstIp, destinationPort) => { string result = "open"; try { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(dstIpAddress, destinationPort); } catch (Exception e) { result = "closed"; } Console.WriteLine("TCP port {0} is {1}.", destinationPort, result); }); using (var pool = new ThreadPool(10)) { for (var i = 0; i < 50; i++) { pool.QueueTask(() => tcpConnect(dstIpAddress,i)); } } 

enter image description here

1
  • Using Resharper will hint you to explicitly capture the var. Great tool Commented Jan 27, 2014 at 14:04

2 Answers 2

2

The i variable is begin caqptured, rather than it's value. Change your loop to:

for (var i = 0; i < 50; i++) { int port = i; pool.QueueTask(() => tcpConnect(dstIpAddress,port)); } 
Sign up to request clarification or add additional context in comments.

Comments

2

Because all but one of your queued tasks are running after the loop has completed, by the time they run, i is always 50. You need to take a local copy of your loop variable:

for (var i = 0; i < 50; i++) { var port = i; pool.QueueTask(() => tcpConnect(dstIpAddress, port)); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.