Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions dotnet/src/webdriver/Internal/PortUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,23 @@ public static class PortUtilities
/// <summary>
/// Finds a random, free port to be listened on.
/// </summary>
/// <remarks>
/// Prefers IPv4, but falls back to IPv6 if necessary.
/// </remarks>
/// <returns>A random, free port to be listened on.</returns>
public static int FindFreePort()
{
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;

try
{
using var ipV4socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ipV4socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
return ((IPEndPoint)ipV4socket.LocalEndPoint!).Port;
}
catch (SocketException)
{
using var ipV6socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
ipV6socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
return ((IPEndPoint)ipV6socket.LocalEndPoint!).Port;
}
}
}
Loading