Send() public method

Sends data to a connected SecureSocket, starting at the indicated location in the data.
is a null reference (Nothing in Visual Basic). The specified size is zero. An operating system error occurs while accessing the SecureSocket. The SecureSocket has been closed. Unable to encrypt the data.
public Send ( byte buffer ) : int
buffer byte The data to be sent.
return int
Ejemplo n.º 1
0
 /// <summary>
 /// Writes data to the stream.
 /// </summary>
 /// <param name="buffer">The data to write to the stream.</param>
 /// <param name="offset">The location in the buffer to start writing data from.</param>
 /// <param name="size">The number of bytes to write to the stream.</param>
 /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="offset"/> or <paramref name="size"/> exceeds the size of <paramref name="buffer"/>.</exception>
 /// <exception cref="IOException">There is a failure while writing to the network.</exception>
 public override void Write(byte[] buffer, int offset, int size)
 {
     if (buffer == null)
     {
         throw new ArgumentNullException();
     }
     if (offset < 0 || offset > buffer.Length || size < 0 || size > buffer.Length - offset)
     {
         throw new ArgumentOutOfRangeException();
     }
     if (Socket == null)
     {
         throw new IOException();
     }
     Socket.Send(buffer, offset, size, SocketFlags.None);
 }
Ejemplo n.º 2
0
		//sendraw SSL
		public string sendraw (string ipRaw, string portRaw, string payloadRaw, int size, int TimeOut, int retry, bool useSSL) {
			
			IPHostEntry IPHost = Dns.Resolve(ipRaw); 
			string []aliases = IPHost.Aliases; 
			IPAddress[] addr = IPHost.AddressList; 
			IPEndPoint iep ;
			SecureProtocol sp;
			sp=SecureProtocol.Ssl3;
			SecureSocket s=null; 
			SecurityOptions options = new SecurityOptions(sp);
			options.Certificate = null;
			options.Protocol=SecureProtocol.Ssl3;
			options.Entity = ConnectionEnd.Client;
			options.CommonName = ipRaw;
			options.VerificationType = CredentialVerification.None;
			options.Flags = SecurityFlags.IgnoreMaxProtocol;
			options.AllowedAlgorithms = SslAlgorithms.ALL;

			while (retry>0){
				try {
				
					s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
					s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 4000);
					s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 4000);
			
					iep	= new IPEndPoint(addr[0],Convert.ToInt32(portRaw));
					s.Connect(iep);

					ASCIIEncoding asen= new ASCIIEncoding();
					byte[] ba=asen.GetBytes(payloadRaw);
					s.Send(ba,ba.Length,System.Net.Sockets.SocketFlags.None);
					

					byte[] bb=new byte[size];
					
					int k=1;
					string response="";
					while (k>0){
						k=s.Receive(bb,size,System.Net.Sockets.SocketFlags.None);					
						response+=Encoding.Default.GetString(bb,0,k);
					}
					s.Close();
					GC.Collect();
					GC.WaitForPendingFinalizers();

					return response;

				}
				catch(Exception ex) {
					retry--;
					Thread.Sleep(1000);
				}
			}
			
			return "Timeout or retry count exceeded";
		}
Ejemplo n.º 3
0
        public static int SendResponse(SecureSocket socket, byte[] data, int statusCode, string contentType)
        {
            string initialLine = "HTTP/1.1 " + statusCode + " " + StatusCode.GetReasonPhrase(statusCode) + "\r\n";

            var headers = new Dictionary<string,string>();
            if (data.Length > 0)
            {
                headers.Add("Content-Type", contentType);
            }
            else
            {
                initialLine += "\r\n";
            }
            int sent = socket.Send(Encoding.UTF8.GetBytes(initialLine));
            SendHeaders(socket, headers, data.Length);
            if (data.Length > 0)
                sent += socket.Send(data);

            return sent;
        }
Ejemplo n.º 4
0
        //TODO must be reworked
        public static void SendHeaders(SecureSocket socket, Dictionary<string, string> headers, int contentLength = 0)
        {
            var headersString = new StringBuilder();

            foreach (var header in headers)
            {
                headersString.AppendFormat("{0}: {1}\r\n", header.Key, header.Value);
            }
            headersString.AppendFormat("Content-Length: {0}\r\n" + "\r\n", contentLength);
            byte[] headersBytes = Encoding.UTF8.GetBytes(headersString.ToString());
            socket.Send(headersBytes);
        }
Ejemplo n.º 5
0
        public static void Http11DownloadResource(SecureSocket socket, Uri requestUri)
        {
            byte[] headersBytes = Encoding.UTF8.GetBytes(ConstructHeaders(requestUri));
            int sent = socket.Send(headersBytes);

            string[] responseHeaders = ReadHeaders(socket);

            var buffer = new byte[128 * 1024]; //128 kb
            using (var stream = new MemoryStream(128 * 1024))
            {
                while (true)
                {
                    int received = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                    if (received == 0)
                        break;

                    stream.Write(buffer, 0, received);
                }

                var fileBuffer = new byte[stream.Position];
                Buffer.BlockCopy(stream.GetBuffer(), 0, fileBuffer, 0, fileBuffer.Length);
                int fileNameIndex = requestUri.AbsolutePath.LastIndexOf("/");
                string fileName = requestUri.AbsolutePath.Substring(fileNameIndex);

                string directory = AssemblyPath;
                SaveFile(directory, fileName, fileBuffer);

                if (OnDownloadSuccessful != null)
                {
                    OnDownloadSuccessful(null, new Http11ResourceDownloadedEventArgs(fileBuffer.Length, fileName));
                }

                socket.Close();

                if (OnSocketClosed != null)
                {
                    OnSocketClosed(null, new SocketCloseEventArgs());
                }
            }
        }
Ejemplo n.º 6
0
        public string sendraw(string ipRaw, string portRaw, string payloadRaw, int size, int TimeOut, bool useSSL)
        {
            int retry = (int)updownRetryTCP.Value;
            IPHostEntry IPHost = Dns.GetHostEntry(ipRaw);
            //IPHostEntry IPHost = Dns.Resolve(ipRaw); 
            string[] aliases = IPHost.Aliases;
            IPAddress[] addr = IPHost.AddressList;
            IPEndPoint iep;
            SecureProtocol sp;
            sp = SecureProtocol.Ssl3;
            SecureSocket s = null;
            SecurityOptions options = new SecurityOptions(sp);
            options.Certificate = null;
            options.Protocol = SecureProtocol.Ssl3;
            options.Entity = ConnectionEnd.Client;
            options.CommonName = ipRaw;
            options.VerificationType = CredentialVerification.None;
            options.Flags = SecurityFlags.IgnoreMaxProtocol;
            options.AllowedAlgorithms = SslAlgorithms.ALL;

            while (retry > 0)
            {
                try
                {

                    s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
                    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 4000);
                    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 4000);

                    iep = new IPEndPoint(addr[0], Convert.ToInt32(portRaw));


                    s.Connect(iep);


                    ASCIIEncoding asen = new ASCIIEncoding();
                    byte[] ba = asen.GetBytes(payloadRaw);
                    s.Send(ba, ba.Length, System.Net.Sockets.SocketFlags.None);

                    byte[] bb = new byte[size];


                    string response = "";
                    int k = 1;
                    while (k > 0)
                    {
                        k = s.Receive(bb, size, System.Net.Sockets.SocketFlags.None);
                        for (int i = 0; i < k; i++)
                        {
                            response += Convert.ToChar(bb[i]);
                        }
                    }
                    s.Close();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    return response;

                }


                catch
                {
                    retry--;
                    lblStatus.Text = "Network problem - retrying\r\n";
                    lblNiktoAI.Text = "Network problem - retrying\r\n";
                    Thread.Sleep(1000);
                }
            }

            return "Retry count (" + updownRetryTCP.Value.ToString() + ") exceeded";
        }
Ejemplo n.º 7
0
        //TODO must be reworked
        public static void SendHeaders(SecureSocket socket, Dictionary<string, string> headers, int? contentLength = null)
        {
            Contract.Assert(contentLength != null);

            byte[] headersBytes = Encoding.UTF8.GetBytes(string.Format("Content-Length: {0}\r\n" + "\r\n", contentLength));
            socket.Send(headersBytes);
        }
Ejemplo n.º 8
0
        public static void Http11SendResponse(SecureSocket socket)
        {
            string[] headers = GetHttp11Headers(socket);
            string filename = GetFileName(headers);

            //No headers where received
            if (headers.Length == 0)
            {
                socket.Close();
            }

            string path = Path.GetFullPath(AssemblyPath + @"\root" + filename);

            if (!File.Exists(path))
            {
                Console.WriteLine("File " + filename + " not found");
                return;
            }

            try
            {
                using (var sr = new StreamReader(path))
                {
                    string file = sr.ReadToEnd();
                    SendHeaders(socket, null, file.Length);

                    var fileBytes = Encoding.UTF8.GetBytes(file);

                    int sent = socket.Send(fileBytes);
                    Console.WriteLine("Sent: " + sent);
                    Console.WriteLine("File sent: " + filename);

                    socket.Close();

                    if (OnSocketClosed != null)
                    {
                        OnSocketClosed(null, new SocketCloseEventArgs());
                    }
                }
            }
            catch (Exception ex)
            {
                var msgBytes = Encoding.UTF8.GetBytes(ex.Message);
                socket.Send(msgBytes);

                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Download a file using the synchronous Socket methods.
 /// </summary>
 /// <param name="url">The URL to download.
 /// </param>
 /// <param name="sp">The protocol to use.</param>
 protected void DownloadFile(Url url, SecureProtocol sp)
 {
     string request = GetHttpRequest(url); // holds the HTTP request for the given URL
     SecureSocket s;
     try {
         // First we create a new SecurityOptions instance
         // SecurityOptions objects hold information about the security
         // protocols the SecureSocket should use and how the SecureSocket
         // should react in certain situations.
         SecurityOptions options = new SecurityOptions(sp);
         // The Certificate field holds a certificate associated with
         // a client [you, for instance]. Because client certificates
         // are not often used for HTTP over SSL or TLS, we'll simply
         // set this field to a null reference.
         options.Certificate = null;
         // The Entity specifies whether the SecureSocket should act
         // as a client socket or as a server socket. In this case,
         // it should act as a client socket.
         options.Entity = ConnectionEnd.Client;
         // The CommonName field specifies the name of the remote
         // party we're connecting to. This is usually the domain name
         // of the remote host.
         options.CommonName = url.Host;
         // The VerificationType field specifies how we intend to verify
         // the certificate. In this case, we tell the SecureSocket that
         // we will manually verify the certificate. Look in the documentation
         // for other options.
         options.VerificationType = CredentialVerification.Manual;
         // When specifying the CredentialVerification.Manual option, we
         // must also specify a CertVerifyEventHandler delegate that will
         // be called when the SecureSocket receives the remote certificate.
         // The Verifier field holds this delegate. If no manual verification
         // is done, this field can be set to a null reference.
         options.Verifier = new CertVerifyEventHandler(OnVerify);
         // The Flags field specifies which flags should be used for the
         // connection. In this case, we will simply use the default behavior.
         options.Flags = SecurityFlags.Default;
         // Allow only secure ciphers to be used. If the server only supports
         // weak encryption, the connections will be shut down.
         options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;
         // create a new SecureSocket instance and initialize it with
         // the security options we specified above.
         s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // connect to the remote host
         s.Connect(new IPEndPoint(Dns.GetHostEntry(url.Host).AddressList[0], url.Port));
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while connecting: " + e.ToString());
         return;
     }
     // send the HTTP request to the remote host
     Console.Write("HTTP Query string:\r\n------------------\r\n" + request);
     try {
         byte[] reqBytes = Encoding.ASCII.GetBytes(request);
         int sent = s.Send(reqBytes, 0, reqBytes.Length, SocketFlags.None);
         while(sent != reqBytes.Length) {
             sent += s.Send(reqBytes, sent, reqBytes.Length - sent, SocketFlags.None);
         }
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while sending: " + e.ToString());
         return;
     }
     // receive the reply
     Console.WriteLine("HTTP Server reply:\r\n------------------");
     try {
         byte[] buffer = new byte[4096];
         int ret = s.Receive(buffer);
         while(ret != 0) {
             Console.Write(Encoding.ASCII.GetString(buffer, 0, ret));
             ret = s.Receive(buffer);
         }
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while receiving: " + e.ToString());
         return;
     }
     try {
         s.Shutdown(SocketShutdown.Both); // shut down the TCP connection
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while shutting the connection down: " + e.ToString());
         return;
     }
     s.Close();
 }