//返回 0:失败 startPort~endPort:成功
private int FindNextAvailableUDPPort(int startPort, int endPort)
{
int port = startPort;
bool isAvailable = true;
IPGlobalProperties ipGlobalProperties =
IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints =
ipGlobalProperties.GetActiveUdpListeners();
do
{
if (!isAvailable)
{
port++;
isAvailable = true;
}
foreach (IPEndPoint endPoint in endPoints)
{
if (endPoint.Port != port)
continue;
isAvailable = false;
break;
}
} while (!isAvailable && port <= endPort);
if (isAvailable == true)
{
return port;
}
else
{
return 0;
}
}