diff --git a/server/src/UdpServer.cs b/server/src/UdpServer.cs index 69d35fc..a779b7d 100644 --- a/server/src/UdpServer.cs +++ b/server/src/UdpServer.cs @@ -123,7 +123,15 @@ public class UDPServer { for (int i = 0; i < num; i++) { - listeners.Add(new UdpClient(this.listenPort + i)); + int currentPort = this.listenPort + i; + if (IsPortInUse(currentPort)) + { + throw new ArgumentException( + $"Port {currentPort} is already in use.", + nameof(port) + ); + } + listeners.Add(new UdpClient(currentPort)); } this.groupEP = new IPEndPoint(IPAddress.Any, listenPort); } @@ -137,6 +145,29 @@ public class UDPServer } } + private bool IsPortInUse(int port) + { + bool inUse = false; + try + { + var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); + var udpListeners = ipGlobalProperties.GetActiveUdpListeners(); + foreach (var ep in udpListeners) + { + if (ep.Port == port) + { + inUse = true; + break; + } + } + } + catch (Exception ex) + { + logger.Warn($"Failed to check port usage for port {port}: {ex.Message}"); + } + return inUse; + } + /// /// 异步寻找目标发送的内容 ///