public Receive ( byte buffer ) : int | ||
buffer | byte | The storage location for the received data. |
return | int |
/// <summary> /// Reads data from the stream. /// </summary> /// <param name="buffer">The location in memory to store data read from the stream.</param> /// <param name="offset">The location in the buffer to begin storing the data to.</param> /// <param name="size">The number of bytes to read from the stream.</param> /// <returns>The number of bytes read from the stream.</returns> /// <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 reading from the network.</exception> public override int Read(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(); } return(Socket.Receive(buffer, offset, size, SocketFlags.None)); }
public static string[] GetHttp11Headers(SecureSocket socket) { var headers = new List<string>(5); var lineBuffer = new byte[1024]; string header = String.Empty; int totalBytesCame = 0; int bytesOfLastHeader = 0; while (true) { bool gotException = false; var bf = new byte[1]; int bytesCame = socket.Receive(bf); if (bytesCame == 0) break; Buffer.BlockCopy(bf, 0, lineBuffer, totalBytesCame, bytesCame); totalBytesCame += bytesCame; try { header = Encoding.UTF8.GetString(lineBuffer, bytesOfLastHeader, totalBytesCame - bytesOfLastHeader); } catch { gotException = true; } if (totalBytesCame != 0 && !gotException && header[header.Length - 1] == '\n') { headers.Add(header.TrimEnd('\n', '\r')); bytesOfLastHeader = totalBytesCame; } // empty header means we got \r\n\r\n which was trimmed. This means end of headers block. if (headers.Count >= 2 && String.IsNullOrEmpty(headers.LastOrDefault())) { break; } } headers.RemoveAll(String.IsNullOrEmpty); return headers.ToArray(); }
//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"; }
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()); } } }
private bool GetSessionHeaderAndVerifyIt(SecureSocket incomingClient) { var sessionHeaderBuffer = new byte[ClientSessionHeader.Length]; int received = incomingClient.Receive(sessionHeaderBuffer, 0, sessionHeaderBuffer.Length, SocketFlags.None); var receivedHeader = Encoding.UTF8.GetString(sessionHeaderBuffer); if (receivedHeader != ClientSessionHeader) { return false; } return true; }
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"; }
private bool GetSessionHeaderAndVerifyIt(SecureSocket incomingClient) { var sessionHeaderBuffer = new byte[ClientSessionHeader.Length]; int received = incomingClient.Receive(sessionHeaderBuffer, 0, sessionHeaderBuffer.Length, SocketFlags.None); var receivedHeader = Encoding.UTF8.GetString(sessionHeaderBuffer); return string.Equals(receivedHeader, ClientSessionHeader, StringComparison.OrdinalIgnoreCase); }
/// <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(); }