Innovenergy_trunk/csharp/lib/Utils/Net/NetUtils.cs

32 lines
939 B
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
using System.Net.NetworkInformation;
namespace InnovEnergy.Lib.Utils.Net;
public static class NetUtils
{
public static Int32 GetAvailableTcpPort()
{
const Int32 minPort = 1024;
var ipProps = IPGlobalProperties.GetIPGlobalProperties();
var tcpConnections = ipProps
.GetActiveTcpConnections()
.Select(c => c.LocalEndPoint.Port)
.Where(p => p >= minPort);
var tcpListeners = ipProps
.GetActiveTcpListeners()
.Select(c => c.Port)
.Where(p => p >= minPort);
var usedPorts = tcpConnections
.Concat(tcpListeners)
.ToHashSet();
return Enumerable
.Range(minPort, UInt16.MaxValue - minPort)
.Unless(usedPorts.Contains)
.First();
}
}