Skip to content
18 changes: 8 additions & 10 deletions dotnet/src/webdriver/Internal/PortUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,18 @@ 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;
using var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
return (socket.LocalEndPoint as IPEndPoint)!.Port;
}
finally
catch (SocketException)
{
portSocket.Close();
// If IPv6 is not supported, fallback to IPv4
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
return (socket.LocalEndPoint as IPEndPoint)!.Port;
}

return listeningPort;
}
}