32 lines
939 B
C#
32 lines
939 B
C#
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();
|
|
}
|
|
} |