当尝试使用已被占用的端口来打开套接字时,会遇到套接字异常。此时,你可以捕获这个异常并尝试增大端口号,例如:
using System.Net;
using System.Net.Sockets;
public class PortOpener
{
private static Socket FindOpenPort(int startPort, int endport)
{
for (int port = startPort; port < endport; port++)
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, port));
return socket;
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.AddressAlreadyInUse) throw;
}
}
return null;
}
public static void Main()
{
var socket = FindOpenPort(8000, 8100);
}
}