Skip to content

Commit 0c9f59f

Browse files
authored
[dotnet] Support IPv6 to find free tcp port via DualMode (#16016)
1 parent 91fc24d commit 0c9f59f

File tree

1 file changed

+4
-17
lines changed

1 file changed

+4
-17
lines changed

dotnet/src/webdriver/Internal/PortUtilities.cs

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -33,23 +33,10 @@ 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.
39-
int listeningPort = 0;
40-
Socket portSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
41-
try
42-
{
43-
IPEndPoint socketEndPoint = new IPEndPoint(IPAddress.Any, 0);
44-
portSocket.Bind(socketEndPoint);
45-
socketEndPoint = (IPEndPoint)portSocket.LocalEndPoint!;
46-
listeningPort = socketEndPoint.Port;
47-
}
48-
finally
49-
{
50-
portSocket.Close();
51-
}
36+
using var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
37+
socket.DualMode = true;
38+
socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
39+
return (socket.LocalEndPoint as IPEndPoint)!.Port;
5240

53-
return listeningPort;
5441
}
5542
}

0 commit comments

Comments
 (0)