You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kev/Drawer/IPCLib/PortHelper.cs

31 lines
801 B
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace IPCLib
{
public static class PortHelper
{
public static int FindAvailablePort(int startPort = 9000, int maxRetry = 100)
{
for (int i = 0; i < maxRetry; i++)
{
int port = startPort + i;
try
{
var listener = new TcpListener(IPAddress.Loopback, port);
listener.Start();
listener.Stop();
return port;
}
catch (SocketException) { }
}
throw new Exception("无法找到可用端口");
}
}
}