0 votes
by (8.4k points)

I would like to build a (very simple) SMTP server using the Rebex.Net.TlsSocket class (inside the Rebex Secure Mail package).

Do you have a sample how to use this class, to get me started how to accept incoming TCP connections ?

1 Answer

+1 vote
by (18.0k points)
Best answer

Below, there is the sample code for a simple TLS/SSL server that accepts a connection, negotiates a session and starts communicating.

To use this code, you need to reference the following libraries:

  • Rebex.Common.dll
  • Rebex.Networking.dll

These two libraries are part of many Rebex components - e.g. Rebex FTP/SSL, Rebex SFTP or Rebex Secure Mail.

using System;
using System.Net;
using System.Net.Sockets;

using Rebex.Net;
using Rebex.Security.Certificates;

namespace Rebex.Samples
    class SimpleSslServer
        // TLS/SSL parameters
        private static TlsParameters _parameters;

        public static void Main()
            // get a certificate with a private key
            Certificate cert = Certificate.LoadPfx(@"c:\cetificate.pfx", "password for the private key");

            // set TLS/SSL parameters:

            _parameters = new TlsParameters();
            // specify this is a server
            _parameters.Entity = TlsConnectionEnd.Server; 
            // choose the ciphers you wish to support
            _parameters.AllowedSuites = TlsCipherSuite.Secure; 
            // construct a certificate chain
            _parameters.Certificate = CertificateChain.BuildFrom(cert);

            // listen on the specified port
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Any, 1234));
            Console.WriteLine("Listening at port {0}.", ((IPEndPoint)socket.LocalEndPoint).Port);

            // accept incoming connection
            socket.BeginAccept(AcceptCallback, socket);

            Console.WriteLine("Press any key to exit");

        // called when a connection is accepted
        private static void AcceptCallback(IAsyncResult ar)
                // finish accepting the connection
                Socket listenSocket = (Socket)ar.AsyncState;
                Socket socket = listenSocket.EndAccept(ar);

                // accept another incoming connection
                listenSocket.BeginAccept(AcceptCallback, listenSocket);

                // create an instance of TlsSocket and negotiate TLS/SSL
                Console.WriteLine("Connection accepted. Negotiating TLS/SSL.");
                TlsSocket tlsSocket = new TlsSocket(socket);
                tlsSocket.Parameters = _parameters;

                Console.WriteLine("TLS/SSL negotiated.");

                // start communicating securely
                // e.g. a protocol communication can be implemented here
            catch (Exception x)
                Console.WriteLine("Error while accepting connection: {0}", x);