我的代码有问题,它工作得很慢
我的代码:
private static void PortRangeScan()
{
Console.Clear();
var From = FROM.Split('.'); // example (103.218.27.85)
string From1 = From[0];
string From2 = From[1];
string From3 = From[2];
string From4 = From[3];
var To = TO.Split('.'); // example (123.218.27.85)
string To1 = To[0];
string To2 = To[1];
string To3 = To[2];
string To4 = To[3];
for (int CurrentProxy = int.Parse(From1); CurrentProxy <= int.Parse(To1); CurrentProxy++)
{
foreach (int s in Ports)
{
TcpClient Scan = new TcpClient();
try
{
// If there is no exception then the Port is open
Scan.Connect($"{CurrentProxy}.{From2}.{From3}.{From4}", s);
Console.WriteLine($"[{CurrentProxy}.{From2}.{From3}.{From4}] | [{s}] | OPEN", Color.Green);
}
catch
{
// If there is an excpetion then it means the Port is closed
Console.WriteLine($"[{CurrentProxy}.{From2}.{From3}.{From4}] | [{s}] | CLOSED", Color.Red);
}
}
}
}
此代码运行速度非常慢,如果端口关闭,则最多可能需要 10 秒才能检查下一个端口。
我想添加一个 Parallel.For 循环或多线程,但我不确定如何使用此代码做到这一点。 那么我需要什么:
如何使此代码更快或如何添加多线程
您可以使用 System.Net.Network Information 命名空间。特别是 IPGlobal 属性类。它可用于返回当前使用的端口的完整列表。
抱歉格式。我在手机上,但这里有一个例子。
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (var tcpi in tcpConnInfoArray)
{
Console.Write($"Port {tcpi.LocalEndPoint.Port} is in use.");
}