diff --git a/dotnet/src/webdriver/Internal/PortUtilities.cs b/dotnet/src/webdriver/Internal/PortUtilities.cs index ba80314622a5f..a739e5ccd32f6 100644 --- a/dotnet/src/webdriver/Internal/PortUtilities.cs +++ b/dotnet/src/webdriver/Internal/PortUtilities.cs @@ -33,23 +33,10 @@ public static class PortUtilities /// A random, free port to be listened on. 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; } }