c# - C# - 带有 IP 地址范围的端口扫描
问题描述
我的代码有问题,运行速度非常慢
我的代码:
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.");
}
推荐阅读
- reactjs - react-hook useFormInput()表单验证不起作用
- c++ - 有关容器构造和释放的问题
- python - 将字符串转换为python中字典列表中的列表
- amazon-redshift - 如何从 REDSHIFT JSON 类型列中提取字段?
- c++ - 如何将指向数组的指针初始化为数组中所有索引的空值
- java - java maven中的多模块项目管理
- javascript - 无法在 Firefox 中获取 SVG 元素的转换属性
- java - 在 java 13 中找不到模块 javafx.base
- google-chrome - 内联内容处置在 Chrome 中不起作用
- c++ - 使用智能指针跟踪可能被删除的数据成员