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

Community
  • 1
  • 1
AlexandruC
  • 3,527
  • 6
  • 51
  • 80

2 Answers2

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));
}
spender
  • 117,338
  • 33
  • 229
  • 351
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));
}
Sean
  • 60,939
  • 11
  • 97
  • 136