using HTEX.ScreenClient.Services; using System.Diagnostics; using System.Management; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace HTEX.ScreenClient { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddHttpClient(); builder.Services.AddHttpContextAccessor(); //CheckOrNewPort(5000) builder.WebHost.UseKestrel(options => { options.ListenAnyIP(CheckOrNewPort(5000), options => {/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline }); builder.Services.AddHostedService(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); } /// /// 检测端口是否可用,如果不可用,则递归调用本方法,直到可用为止 /// /// /// public static int CheckOrNewPort(int port) { if (IsPortAvailable(port)) { return port; } else { return CheckOrNewPort(port + 1); } } /// /// 探测端口是否可用 /// /// /// public static bool IsPortAvailable(int port) { bool isPortAvailable = false; IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); // 本地地址 try { using (Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { // 尝试连接到指定的IP地址和端口 IAsyncResult result = socket.BeginConnect(ipAddress, port, null, null); // 等待连接尝试完成(这里简单地使用Socket的ConnectTimeout,但更常见的做法是使用超时等待或异步回调) bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1), true); if (success) { // 如果连接成功,则端口被占用 socket.EndConnect(result); isPortAvailable = false; // 可选:如果需要,可以在这里关闭连接 //socket.Shutdown(SocketShutdown.Both); //socket.Close(); } else { isPortAvailable = true; } } } catch (SocketException ex) { Console.WriteLine($"{ex.Message},{ex.SocketErrorCode}"); // 如果错误代码为10048,则表示地址已被使用 if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse) { isPortAvailable = false; } if (ex.SocketErrorCode==SocketError.ConnectionRefused) { isPortAvailable=true; } } catch (Exception ex) { Console.WriteLine(ex.Message); isPortAvailable = false; } return isPortAvailable; } } }