Skip to content

Commit 2ca4b3f

Browse files
committed
Added comments
1 parent fad7d42 commit 2ca4b3f

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

src/MongoDB.Driver/Core/Connections/Socks5Helper.cs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -141,31 +141,22 @@ public static void PerformSocks5Handshake(Stream stream, EndPoint endPoint, stri
141141
buffer[2] = 0x00;
142142
var addressLength = 0;
143143

144-
//TODO Can we avoid doing this...?
145144
if (IPAddress.TryParse(targetHost, out var ip))
146145
{
147146
switch (ip.AddressFamily)
148147
{
149148
case AddressFamily.InterNetwork:
150149
buffer[3] = AddressTypeIPv4;
151-
#if NET472
152150
Array.Copy(ip.GetAddressBytes(), 0, buffer, 4, 4);
153-
#else
154-
ip.TryWriteBytes(buffer.AsSpan(4), out _);
155-
#endif
156151
addressLength = 4;
157152
break;
158153
case AddressFamily.InterNetworkV6:
159154
buffer[3] = AddressTypeIPv6;
160-
#if NET472
161155
Array.Copy(ip.GetAddressBytes(), 0, buffer, 4, 16);
162-
#else
163-
ip.TryWriteBytes(buffer.AsSpan(4), out _);
164-
#endif
165156
addressLength = 16;
166157
break;
167158
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.");
169160
}
170161
}
171162
else
@@ -188,13 +179,16 @@ public static void PerformSocks5Handshake(Stream stream, EndPoint endPoint, stri
188179
// +----+-----+-------+------+----------+----------+
189180
// | 1 | 1 | X'00' | 1 | Variable | 2 |
190181
// +----+-----+-------+------+----------+----------+
182+
183+
// We read also the first byte of the address, as it contains the length of the address if it is a domain.
191184
stream.ReadBytes(buffer, 0,5, cancellationToken);
192185
VerifyProtocolVersion(buffer[0]);
193186
if (buffer[1] != Socks5Success)
194187
{
195188
throw new IOException($"SOCKS5 connect failed with code 0x{buffer[1]:X2}");
196189
}
197190

191+
// We need to skip the address length minus 1, because we ready already the first byte of the address before
198192
var skip = buffer[3] switch
199193
{
200194
AddressTypeIPv4 => 5,
@@ -203,8 +197,8 @@ public static void PerformSocks5Handshake(Stream stream, EndPoint endPoint, stri
203197
_ => throw new IOException("Unknown address type in SOCKS5 reply.")
204198
};
205199

200+
// Address and port in response are read, but ignored.
206201
stream.ReadBytes(buffer, 0, skip, cancellationToken);
207-
// Address and port in response are ignored
208202
}
209203
finally
210204
{

0 commit comments

Comments
 (0)