@@ -20,7 +20,7 @@ public class TcpClient : IDisposable
20
20
private bool _active ;
21
21
22
22
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
23
- public TcpClient ( ) : this ( AddressFamily . InterNetwork )
23
+ public TcpClient ( ) : this ( AddressFamily . Unknown )
24
24
{
25
25
}
26
26
@@ -31,7 +31,8 @@ public TcpClient(AddressFamily family)
31
31
32
32
// Validate parameter
33
33
if ( family != AddressFamily . InterNetwork &&
34
- family != AddressFamily . InterNetworkV6 )
34
+ family != AddressFamily . InterNetworkV6 &&
35
+ family != AddressFamily . Unknown )
35
36
{
36
37
throw new ArgumentException ( SR . Format ( SR . net_protocol_invalid_family , "TCP" ) , nameof ( family ) ) ;
37
38
}
@@ -111,7 +112,11 @@ protected bool Active
111
112
public Socket Client
112
113
{
113
114
get { return _clientSocket ; }
114
- set { _clientSocket = value ; }
115
+ set
116
+ {
117
+ _clientSocket = value ;
118
+ _family = _clientSocket ? . AddressFamily ?? AddressFamily . Unknown ;
119
+ }
115
120
}
116
121
117
122
public bool Connected => _clientSocket ? . Connected ?? false ;
@@ -186,7 +191,7 @@ public void Connect(string hostname, int port)
186
191
_active = true ;
187
192
break ;
188
193
}
189
- else if ( address . AddressFamily == _family )
194
+ else if ( address . AddressFamily == _family || _family == AddressFamily . Unknown )
190
195
{
191
196
// Only use addresses with a matching family
192
197
Connect ( new IPEndPoint ( address , port ) ) ;
@@ -257,6 +262,7 @@ public void Connect(IPEndPoint remoteEP)
257
262
}
258
263
259
264
Client . Connect ( remoteEP ) ;
265
+ _family = Client . AddressFamily ;
260
266
_active = true ;
261
267
262
268
if ( NetEventSource . IsEnabled ) NetEventSource . Exit ( this ) ;
@@ -267,6 +273,7 @@ public void Connect(IPAddress[] ipAddresses, int port)
267
273
if ( NetEventSource . IsEnabled ) NetEventSource . Enter ( this , ipAddresses ) ;
268
274
269
275
Client . Connect ( ipAddresses , port ) ;
276
+ _family = Client . AddressFamily ;
270
277
_active = true ;
271
278
272
279
if ( NetEventSource . IsEnabled ) NetEventSource . Exit ( this ) ;
@@ -468,7 +475,19 @@ public bool NoDelay
468
475
private void InitializeClientSocket ( )
469
476
{
470
477
Debug . Assert ( _clientSocket == null ) ;
471
- _clientSocket = new Socket ( _family , SocketType . Stream , ProtocolType . Tcp ) ;
478
+ if ( _family == AddressFamily . Unknown )
479
+ {
480
+ // If AF was not explicitly set try to initialize dual mode socket or fall-back to IPv4.
481
+ _clientSocket = new Socket ( SocketType . Stream , ProtocolType . Tcp ) ;
482
+ if ( _clientSocket . AddressFamily == AddressFamily . InterNetwork )
483
+ {
484
+ _family = AddressFamily . InterNetwork ;
485
+ }
486
+ }
487
+ else
488
+ {
489
+ _clientSocket = new Socket ( _family , SocketType . Stream , ProtocolType . Tcp ) ;
490
+ }
472
491
}
473
492
}
474
493
}
0 commit comments