|
1 | 1 | using System.Net; |
| 2 | +using System.Net.NetworkInformation; |
| 3 | +using System.Net.Sockets; |
2 | 4 | using System.Security.Cryptography.X509Certificates; |
3 | 5 | using System.Text.Json.Serialization; |
4 | 6 | using System.Windows.Forms; |
@@ -60,6 +62,33 @@ private static X509Certificate2 GetCert() |
60 | 62 | return cert; |
61 | 63 | } |
62 | 64 |
|
| 65 | + private static bool IsPortAvailable(int port) |
| 66 | + { |
| 67 | + var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); |
| 68 | + var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); |
| 69 | + Console.WriteLine(string.Join(", ", tcpConnInfoArray.Select(tcpi => tcpi.LocalEndPoint.Port.ToString()))); |
| 70 | + foreach (var tcpi in tcpConnInfoArray) |
| 71 | + { |
| 72 | + if (tcpi.LocalEndPoint.Port == port) |
| 73 | + { |
| 74 | + return false; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return true; |
| 79 | + } |
| 80 | + |
| 81 | + private static int GetAvailablePort() |
| 82 | + { |
| 83 | + var port = 49182; |
| 84 | + while (!IsPortAvailable(port)) |
| 85 | + { |
| 86 | + port++; |
| 87 | + } |
| 88 | + |
| 89 | + return port; |
| 90 | + } |
| 91 | + |
63 | 92 | public static void StartApp(bool export, Action? onStart = null) |
64 | 93 | { |
65 | 94 | var builder = WebApplication.CreateBuilder(); |
@@ -92,7 +121,7 @@ public static void StartApp(bool export, Action? onStart = null) |
92 | 121 | # if !DEBUG |
93 | 122 | builder.WebHost.ConfigureKestrel((context, serverOptions) => |
94 | 123 | { |
95 | | - serverOptions.Listen(IPAddress.Loopback, 0); |
| 124 | + serverOptions.Listen(IPAddress.Loopback, GetAvailablePort()); |
96 | 125 | if (export) |
97 | 126 | { |
98 | 127 | serverOptions.Listen(IPAddress.Any, 5001, listenOptions => |
|
0 commit comments