@@ -210,6 +210,10 @@ internal sealed class MirroredWslPortLease : IDisposable
210210 public const int CandidateRangeStart = 20_000 ;
211211 public const int CandidateRangeEnd = 39_999 ;
212212 private const int CandidateCount = CandidateRangeEnd - CandidateRangeStart + 1 ;
213+ internal static IReadOnlyList < IPAddress > BindProbeAddresses { get ; } =
214+ Socket . OSSupportsIPv6
215+ ? [ IPAddress . Loopback , IPAddress . IPv6Loopback ]
216+ : [ IPAddress . Loopback ] ;
213217
214218 private FileStream ? _leaseStream ;
215219
@@ -234,7 +238,7 @@ public static MirroredWslPortLease Acquire()
234238 return Acquire (
235239 CreateCandidateSequence ( startOffset ) ,
236240 windowsPortState ,
237- CanBindExclusively ,
241+ CanBindLoopbackExclusively ,
238242 leaseDirectory ) ;
239243 }
240244
@@ -308,22 +312,17 @@ public void Dispose()
308312 Interlocked . Exchange ( ref _leaseStream , null ) ? . Dispose ( ) ;
309313 }
310314
311- private static bool CanBindExclusively ( int port )
315+ internal static bool CanBindLoopbackExclusively ( int port )
312316 {
313- TcpListener ? ipv4 = null ;
314- TcpListener ? ipv6 = null ;
317+ var listeners = new List < TcpListener > ( BindProbeAddresses . Count ) ;
315318 try
316319 {
317- ipv4 = new TcpListener ( IPAddress . Any , port ) ;
318- ipv4 . Server . ExclusiveAddressUse = true ;
319- ipv4 . Start ( ) ;
320-
321- if ( Socket . OSSupportsIPv6 )
320+ foreach ( var address in BindProbeAddresses )
322321 {
323- ipv6 = new TcpListener ( IPAddress . IPv6Any , port ) ;
324- ipv6 . Server . DualMode = false ;
325- ipv6 . Server . ExclusiveAddressUse = true ;
326- ipv6 . Start ( ) ;
322+ var listener = new TcpListener ( address , port ) ;
323+ listeners . Add ( listener ) ;
324+ listener . Server . ExclusiveAddressUse = true ;
325+ listener . Start ( ) ;
327326 }
328327
329328 return true ;
@@ -334,8 +333,8 @@ private static bool CanBindExclusively(int port)
334333 }
335334 finally
336335 {
337- ipv6 ? . Stop ( ) ;
338- ipv4 ? . Stop ( ) ;
336+ foreach ( var listener in listeners )
337+ listener . Stop ( ) ;
339338 }
340339 }
341340}
0 commit comments