@@ -33,30 +33,19 @@ public static class PortUtilities
33
33
/// <returns>A random, free port to be listened on.</returns>
34
34
public static int FindFreePort ( )
35
35
{
36
- // Prefer IPv6 dual-mode when available , but fall back robustly to IPv4
36
+ // Prefer IPv4 , but fall back robustly to IPv6
37
37
try
38
38
{
39
- using var ipV6socket = new Socket ( AddressFamily . InterNetworkV6 , SocketType . Stream , ProtocolType . Tcp ) ;
40
-
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
39
using var ipV4socket = new Socket ( AddressFamily . InterNetwork , SocketType . Stream , ProtocolType . Tcp ) ;
58
40
ipV4socket . Bind ( new IPEndPoint ( IPAddress . Loopback , 0 ) ) ;
59
41
return ( ( IPEndPoint ) ipV4socket . LocalEndPoint ! ) . Port ;
60
42
}
43
+ catch ( SocketException )
44
+ {
45
+ // If creating/binding the IPv4 socket fails for any reason, fall back to IPv6
46
+ using var ipV6socket = new Socket ( AddressFamily . InterNetworkV6 , SocketType . Stream , ProtocolType . Tcp ) ;
47
+ ipV6socket . Bind ( new IPEndPoint ( IPAddress . IPv6Loopback , 0 ) ) ;
48
+ return ( ( IPEndPoint ) ipV6socket . LocalEndPoint ! ) . Port ;
49
+ }
61
50
}
62
51
}
0 commit comments