2014-01-27 91 views
0

我試圖做一個簡單的TCP端口掃描使用套接字連接,我使用線程池,但我沒有得到我期望的輸出,線程池的代碼來自here線程池不按預期工作

我的代碼:

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

+0

使用resharper會提示你明確地捕獲var。偉大的工具 – Samuel

回答

2

i變量是開始caqptured,而不是它的價值。改變你的循環爲:

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

因爲所有,但你排隊的任務之一的循環完成後,由它們運行的​​時間都在運行,我始終是50元。你需要採取您的循環變量的本地副本:

for (var i = 0; i < 50; i++) 
{ 
    var port = i; 

    pool.QueueTask(() => tcpConnect(dstIpAddress, port)); 
}