File tree Expand file tree Collapse file tree 1 file changed +24
-4
lines changed
dotnet/src/webdriver/Internal Expand file tree Collapse file tree 1 file changed +24
-4
lines changed Original file line number Diff line number Diff line change @@ -33,10 +33,30 @@ public static class PortUtilities
3333 /// <returns>A random, free port to be listened on.</returns>
3434 public static int FindFreePort ( )
3535 {
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 ;
36+ // Prefer IPv6 dual-mode when available, but fall back robustly to IPv4
37+ try
38+ {
39+ using var ipV6socket = new Socket ( AddressFamily . InterNetworkV6 , SocketType . Stream , ProtocolType . Tcp ) ;
4040
41+ // Some platforms may not support DualMode or IPv6 at all; ignore failures and let bind decide
42+ try
43+ {
44+ ipV6socket . DualMode = true ;
45+ }
46+ catch
47+ {
48+ // Ignored; we'll still attempt to bind to IPv6 loopback
49+ }
50+
51+ ipV6socket . Bind ( new IPEndPoint ( IPAddress . IPv6Loopback , 0 ) ) ;
52+ return ( ( IPEndPoint ) ipV6socket . LocalEndPoint ! ) . Port ;
53+ }
54+ catch ( SocketException )
55+ {
56+ // If creating/binding the IPv6 socket fails for any reason, fall back to IPv4
57+ using var ipV4socket = new Socket ( AddressFamily . InterNetwork , SocketType . Stream , ProtocolType . Tcp ) ;
58+ ipV4socket . Bind ( new IPEndPoint ( IPAddress . Loopback , 0 ) ) ;
59+ return ( ( IPEndPoint ) ipV4socket . LocalEndPoint ! ) . Port ;
60+ }
4161 }
4262}
You can’t perform that action at this time.
0 commit comments