Skip to content

Commit 264d1af

Browse files
committed
Fine tuned and verified
1 parent c37403d commit 264d1af

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

dotnet/src/webdriver/Internal/PortUtilities.cs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,23 +33,21 @@ public static class PortUtilities
3333
/// <returns>A random, free port to be listened on.</returns>
3434
public static int FindFreePort()
3535
{
36+
// Locate a free port on the local machine by binding a socket to
37+
// an IPEndPoint using IPAddress.Any and port 0. The socket will
38+
// select a free port.
3639
try
3740
{
38-
var listener = new TcpListener(IPAddress.IPv6Any, 0);
39-
listener.Server.DualMode = true; // Listen on both IPv4 and IPv6
40-
listener.Start();
41-
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
42-
listener.Stop();
43-
return port;
41+
using var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
42+
socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
43+
return (socket.LocalEndPoint as IPEndPoint)!.Port;
4444
}
4545
catch (SocketException)
4646
{
47-
// If IPv6Any is not supported, fallback to IPv4
48-
var listener = new TcpListener(IPAddress.Any, 0);
49-
listener.Start();
50-
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
51-
listener.Stop();
52-
return port;
47+
// If IPv6 is not supported, fallback to IPv4
48+
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
49+
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
50+
return (socket.LocalEndPoint as IPEndPoint)!.Port;
5351
}
5452
}
5553
}

0 commit comments

Comments
 (0)