如何在C# .NET Core 6中获取Windows TCP动态端口范围?
在.NET Core 6中获取Windows TCP动态端口范围
由于微软没有提供直接获取TCP动态端口范围的官方API,你可以通过以下两种方式实现需求:
方法一:读取Windows注册表(推荐)
Windows系统的TCP动态端口配置存储在注册表中,直接读取效率更高,无需启动外部进程。默认起始端口为49152,默认端口数量为16384,若注册表中不存在对应键值则使用默认值。
代码示例:
using Microsoft.Win32; public static (int StartPort, int NumPorts) GetTcpDynamicPortRange() { const string registryPath = @"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"; int startPort = 49152; int numPorts = 16384; using var registryKey = Registry.LocalMachine.OpenSubKey(registryPath); if (registryKey != null) { // 读取起始端口 if (registryKey.GetValue("TcpStartPort") is int portValue) { startPort = portValue; } // 读取端口数量 if (registryKey.GetValue("TcpNumPorts") is int countValue) { numPorts = countValue; } } return (startPort, numPorts); }
方法二:执行netsh命令并解析输出
这种方式直接对应你提到的netsh int ipv4 show dynamicport tcp命令,需注意不同语言版本的Windows输出文本不同,需要兼容多语言解析。
代码示例:
using System.Diagnostics; using System.Text.RegularExpressions; public static (int? StartPort, int? NumPorts) GetTcpDynamicPortRangeViaNetsh() { int? startPort = null; int? numPorts = null; var processInfo = new ProcessStartInfo { FileName = "netsh", Arguments = "int ipv4 show dynamicport tcp", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; using var process = Process.Start(processInfo); if (process != null) { string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); // 匹配中文/英文输出的起始端口 var startMatch = Regex.Match(output, @"起始端口:\s*(\d+)"); if (!startMatch.Success) { startMatch = Regex.Match(output, @"Start Port:\s*(\d+)"); } if (startMatch.Success && int.TryParse(startMatch.Groups[1].Value, out int port)) { startPort = port; } // 匹配中文/英文输出的端口数量 var numMatch = Regex.Match(output, @"端口数量:\s*(\d+)"); if (!numMatch.Success) { numMatch = Regex.Match(output, @"Number of ports:\s*(\d+)"); } if (numMatch.Success && int.TryParse(numMatch.Groups[1].Value, out int count)) { numPorts = count; } } return (startPort, numPorts); }
注意事项
- 注册表读取方式需确保程序有足够权限访问
HKLM路径(普通用户通常具备读取权限)。 netsh命令方式需考虑系统语言差异,若需支持更多语言,需扩展正则表达式匹配规则。- 两种方法仅适用于Windows系统,.NET Core跨平台特性下需先判断当前操作系统类型。
内容的提问来源于stack exchange,提问作者Zerek
相关产品推荐
相关产品推荐

