feat: 添加了端口占用检测,若被占用则不会启动
This commit is contained in:
		@@ -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;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /// <summary>
 | 
			
		||||
    /// 异步寻找目标发送的内容
 | 
			
		||||
    /// </summary>
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user