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));
}
}
使用resharper會提示你明確地捕獲var。偉大的工具 – Samuel