@@ -141,31 +141,22 @@ public static void PerformSocks5Handshake(Stream stream, EndPoint endPoint, stri
141
141
buffer [ 2 ] = 0x00 ;
142
142
var addressLength = 0 ;
143
143
144
- //TODO Can we avoid doing this...?
145
144
if ( IPAddress . TryParse ( targetHost , out var ip ) )
146
145
{
147
146
switch ( ip . AddressFamily )
148
147
{
149
148
case AddressFamily . InterNetwork :
150
149
buffer [ 3 ] = AddressTypeIPv4 ;
151
- #if NET472
152
150
Array . Copy ( ip . GetAddressBytes ( ) , 0 , buffer , 4 , 4 ) ;
153
- #else
154
- ip . TryWriteBytes ( buffer . AsSpan ( 4 ) , out _ ) ;
155
- #endif
156
151
addressLength = 4 ;
157
152
break ;
158
153
case AddressFamily . InterNetworkV6 :
159
154
buffer [ 3 ] = AddressTypeIPv6 ;
160
- #if NET472
161
155
Array . Copy ( ip . GetAddressBytes ( ) , 0 , buffer , 4 , 16 ) ;
162
- #else
163
- ip . TryWriteBytes ( buffer . AsSpan ( 4 ) , out _ ) ;
164
- #endif
165
156
addressLength = 16 ;
166
157
break ;
167
158
default :
168
- throw new IOException ( "Invalid target host address family. Only IPv4 and IPv6 are supported. " ) ;
159
+ throw new IOException ( "Invalid target host address family." ) ;
169
160
}
170
161
}
171
162
else
@@ -188,13 +179,16 @@ public static void PerformSocks5Handshake(Stream stream, EndPoint endPoint, stri
188
179
// +----+-----+-------+------+----------+----------+
189
180
// | 1 | 1 | X'00' | 1 | Variable | 2 |
190
181
// +----+-----+-------+------+----------+----------+
182
+
183
+ // We read also the first byte of the address, as it contains the length of the address if it is a domain.
191
184
stream . ReadBytes ( buffer , 0 , 5 , cancellationToken ) ;
192
185
VerifyProtocolVersion ( buffer [ 0 ] ) ;
193
186
if ( buffer [ 1 ] != Socks5Success )
194
187
{
195
188
throw new IOException ( $ "SOCKS5 connect failed with code 0x{ buffer [ 1 ] : X2} ") ;
196
189
}
197
190
191
+ // We need to skip the address length minus 1, because we ready already the first byte of the address before
198
192
var skip = buffer [ 3 ] switch
199
193
{
200
194
AddressTypeIPv4 => 5 ,
@@ -203,8 +197,8 @@ public static void PerformSocks5Handshake(Stream stream, EndPoint endPoint, stri
203
197
_ => throw new IOException ( "Unknown address type in SOCKS5 reply." )
204
198
} ;
205
199
200
+ // Address and port in response are read, but ignored.
206
201
stream . ReadBytes ( buffer , 0 , skip , cancellationToken ) ;
207
- // Address and port in response are ignored
208
202
}
209
203
finally
210
204
{
0 commit comments