56 lines
1.3 KiB
C#
56 lines
1.3 KiB
C#
using System;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
|
|
namespace Laservall.Solidworks.Server
|
|
{
|
|
internal static class PortFinder
|
|
{
|
|
private const int PreferredPort = 18951;
|
|
|
|
public static int FindAvailablePort()
|
|
{
|
|
if (IsPortAvailable(PreferredPort))
|
|
{
|
|
return PreferredPort;
|
|
}
|
|
|
|
return GetOsAssignedPort();
|
|
}
|
|
|
|
private static bool IsPortAvailable(int port)
|
|
{
|
|
TcpListener listener = null;
|
|
try
|
|
{
|
|
listener = new TcpListener(IPAddress.Loopback, port);
|
|
listener.Start();
|
|
return true;
|
|
}
|
|
catch (SocketException)
|
|
{
|
|
return false;
|
|
}
|
|
finally
|
|
{
|
|
listener?.Stop();
|
|
}
|
|
}
|
|
|
|
private static int GetOsAssignedPort()
|
|
{
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
try
|
|
{
|
|
listener.Start();
|
|
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
return port;
|
|
}
|
|
finally
|
|
{
|
|
listener.Stop();
|
|
}
|
|
}
|
|
}
|
|
}
|