Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sockets and SslStreams

Tags:

c#

ssl

sockets

I'm confused as to what is "best" to use when dealing with sockets. The Socket object provides Send/Receive methods (and async equivalents), but also allows a NetworkStream to be created. The only way I've had any joy using Socket.Send is by wrapping the call in a block such as:


using (Stream stream = new NetworkStream(socket)) {
  socket.Send(...);
  stream.Flush();
}

When using SslStream, if you send a message on the underlying socket, will it be sent over SSL? Should I just use Stream.Write(...) rather than the socket methods?

Thanks.

like image 883
Chris Cooper Avatar asked Sep 16 '10 09:09

Chris Cooper


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

Rules of thumb:

  • If you're not using a NetworkStream, use the Socket.Send/Socket.Receive methods.
  • If you're using a NetworkStream (which is wrapping the Socket), use the NetworkStream.Read/Write methods but don't call the Socket methods.
  • If you're wrapping a NetworkStream in an SslStream, use the NetworkStream.Read/Write methods before calling AuthenticateAsClient/Server, and the SslStream.Read/Write methods after.

After AuthenticateAsClient/Server, your connection will be SSL secured. Don't call the Socket or NetworkStream methods then: this will break the SslStream.

(It's possible to ignore these rules under certain circumstances, but then you need to be really careful and precisely know what Socket, NetworkStream and SslStream do under the hood. If you always use the outermost wrapper, you're on the safe side.)

like image 112
dtb Avatar answered Sep 28 '22 16:09

dtb