private bool SendProxyConnectProtocol(TelegramExchangerHost serverAddressPair)
        {
            // SOCKS 4 Protocol
            // +----+----+----+----+----+----+----+----+----+----+....+----+
            // | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
            // +----+----+----+----+----+----+----+----+----+----+....+----+
            //    1    1      2              4           variable       1

            byte[] buffer = new byte[14];

            buffer[0] = 0x04; // VN
            buffer[1] = 0x01; // CD, 1:CONNECT request,2: BIND request

            // DSTPORT
            UInt16 port = Convert.ToUInt16(serverAddressPair.Port);

            byte[] portBytes = BitConverter.GetBytes(port);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(portBytes);
            }
            Array.Copy(portBytes, 0, buffer, 2, 2);

            // DSTIP
            string[] ipAddresses = serverAddressPair.Host.Split('.');
            byte[]   ipBytes     = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                ipBytes[i] = Byte.Parse(ipAddresses[i]);
            }
            Array.Copy(ipBytes, 0, buffer, 4, 4);

            // USERID : using default user name "guest"
            byte[] userIDBytes = Encoding.UTF8.GetBytes("guest");
            Array.Copy(userIDBytes, 0, buffer, 8, 5);

            // add c++ string terminated
            buffer[13] = 0x00;

            var sendResult = ClientSocket.Send(buffer);

            if (!sendResult)
            {
                OnErrorOccured();
            }

            return(sendResult);
        }
        private bool ConnectThroughProxy(TelegramExchangerHost serverAddressPair)
        {
            if (!ConnectProxy())
            {
                return(false);
            }

            if (!SendProxyConnectProtocol(serverAddressPair))
            {
                return(false);
            }

            if (!ReceiveProxyConnectResult())
            {
                return(false);
            }

            return(true);
        }
 private bool ConnectDirect(TelegramExchangerHost serverAddressPair)
 {
     return(ClientSocket.Connect(serverAddressPair.Host, serverAddressPair.Port));
 }