Skip to content
21 changes: 4 additions & 17 deletions dotnet/src/webdriver/Internal/PortUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,23 +33,10 @@ public static class PortUtilities
/// <returns>A random, free port to be listened on.</returns>
public static int FindFreePort()
{
// Locate a free port on the local machine by binding a socket to
// an IPEndPoint using IPAddress.Any and port 0. The socket will
// select a free port.
int listeningPort = 0;
Socket portSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPEndPoint socketEndPoint = new IPEndPoint(IPAddress.Any, 0);
portSocket.Bind(socketEndPoint);
socketEndPoint = (IPEndPoint)portSocket.LocalEndPoint!;
listeningPort = socketEndPoint.Port;
}
finally
{
portSocket.Close();
}
using var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
socket.DualMode = true;
socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
return (socket.LocalEndPoint as IPEndPoint)!.Port;

return listeningPort;
}
}