File tree Expand file tree Collapse file tree 1 file changed +15
-5
lines changed
dotnet/src/webdriver/Internal Expand file tree Collapse file tree 1 file changed +15
-5
lines changed Original file line number Diff line number Diff line change @@ -30,13 +30,23 @@ public static class PortUtilities
30
30
/// <summary>
31
31
/// Finds a random, free port to be listened on.
32
32
/// </summary>
33
+ /// <remarks>
34
+ /// Prefers IPv4, but falls back to IPv6 if necessary.
35
+ /// </remarks>
33
36
/// <returns>A random, free port to be listened on.</returns>
34
37
public static int FindFreePort ( )
35
38
{
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 ;
40
-
39
+ try
40
+ {
41
+ using var ipV4socket = new Socket ( AddressFamily . InterNetwork , SocketType . Stream , ProtocolType . Tcp ) ;
42
+ ipV4socket . Bind ( new IPEndPoint ( IPAddress . Loopback , 0 ) ) ;
43
+ return ( ( IPEndPoint ) ipV4socket . LocalEndPoint ! ) . Port ;
44
+ }
45
+ catch ( SocketException )
46
+ {
47
+ using var ipV6socket = new Socket ( AddressFamily . InterNetworkV6 , SocketType . Stream , ProtocolType . Tcp ) ;
48
+ ipV6socket . Bind ( new IPEndPoint ( IPAddress . IPv6Loopback , 0 ) ) ;
49
+ return ( ( IPEndPoint ) ipV6socket . LocalEndPoint ! ) . Port ;
50
+ }
41
51
}
42
52
}
You can’t perform that action at this time.
0 commit comments