feat: 添加了端口占用检测,若被占用则不会启动

This commit is contained in:
SikongJueluo 2025-07-17 11:23:45 +08:00
parent e3b769b24e
commit dfe279bf37
No known key found for this signature in database
1 changed files with 32 additions and 1 deletions

View File

@ -123,7 +123,15 @@ public class UDPServer
{ {
for (int i = 0; i < num; i++) 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); 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>
/// 异步寻找目标发送的内容 /// 异步寻找目标发送的内容
/// </summary> /// </summary>