提供一个以C#为语法,描述SOCET5协议通信的过程示例:

提供一个以C#为语法,描述SOCET5协议通信的过程示例:



/// <summary>
/// 构建一个通过代理服务器与目标服务器进行TCP通信的CTcpClient对象
/// </summary>
/// <param name="proxyIP">代理服务器IP</param>
/// <param name="proxyPort">代理服务器端口号</param>
/// <param name="destIPOrDomain">目标服务器域名</param>
/// <param name="destPort">目标服务器端口号</param>
/// <returns></returns>
static public CTcpClient ConnectProxyServer(string proxyIP, int proxyPort, string destIPOrDomain, int destPort)
{
CTcpClient tcpClient = new CTcpClient();
if (tcpClient != null)
{
if (!tcpClient.Start(proxyPort, proxyIP))
{
return null;
}

{//# 认证阶段
byte[] szFlagAuthenticationPhase1 = new byte[3] { 0x05, 0x01, 0x00 };
tcpClient.Send(szFlagAuthenticationPhase1, 0, 3);
byte[] szFlagAuthenticationPhase2 = new byte[3] { 0, 0, 0 };
tcpClient.Receive(szFlagAuthenticationPhase2, 0, 2);
if (0x05 != szFlagAuthenticationPhase2[0] || 0x00 != szFlagAuthenticationPhase2[1])
{
tcpClient.Close();
tcpClient = null;
return null;
}
}

{//目标地址提交
//标志
byte[] szFlagAuthenticationPhase1 = new byte[4] { 0x05, 0x01, 0x00, 0x03 };
tcpClient.Send(szFlagAuthenticationPhase1, 0, 4);

//域名长度和域名
byte[] data = Encoding.UTF8.GetBytes(destIPOrDomain);
byte[] destIPLen = new byte[1];
destIPLen[0] = (byte)(data.Length);
tcpClient.Send(destIPLen, 0, 1);
tcpClient.Send(data, 0, data.Length);

//端口号
Int16 i = (Int16)destPort;
byte[] shi = System.BitConverter.GetBytes(i);
byte t = shi[0];
shi[0] = shi[1];
shi[1] = t;
tcpClient.Send(shi, 0, 2);
}

{//代理服务器返回
byte[] szRelValue1 = new byte[5];
tcpClient.Receive(szRelValue1, 0, 5);
if (0x05 != szRelValue1[0] ||
0x00 != szRelValue1[1] ||
0x00 != szRelValue1[2] ||
0x03 != szRelValue1[3])
{
tcpClient.Close();
tcpClient = null;
return null;
}
byte ipLen = szRelValue1[4];

byte[] szRelValue2 = new byte[ipLen];
tcpClient.Receive(szRelValue2, 0, ipLen);

byte[] portBytes = new byte[2];
tcpClient.Receive(portBytes, 0, 2);

byte b = portBytes[0];
portBytes[0] = portBytes[1];
portBytes[1] = b;

Int16 port = BitConverter.ToInt16(portBytes, 0);

if (port != (Int16)destPort)
{
tcpClient.Close();
tcpClient = null;
return null;
}
}
}
return tcpClient;
}