SslProtocolDirection Enum

Specifies the direction of SSL/TLS communication.

public enum SslProtocolDirection

Members

  • Any - Specifies that the direction can be either client or server.
  • Client - Specifies that the direction is client-side.
  • Server - Specifies that the direction is server-side.

Remarks

The SslProtocolDirection enumeration is used by the SslStream class to determine whether to create an SSL/TLS stream for a client or a server.

When you set the SslStream to operate in client mode, it attempts to authenticate the server. When you set it to operate in server mode, it attempts to authenticate the client.

The Any value indicates that the SslStream can be used for either client or server authentication, allowing for flexibility in connection setup.

Requirements

Namespace: System.Net.Security

Assembly: System.Net.Security.dll

Example

The following code example shows how to create an SslStream that operates in client mode.


using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;

public class Example
{
    public static void Main(string[] args)
    {
        try
        {
            TcpClient client = new TcpClient("www.example.com", 443);
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
            );

            // Authenticate the server
            sslStream.AuthenticateAsClient("www.example.com", null, System.Security.Authentication.SslProtocols.Tls12, false);

            Console.WriteLine("SSL stream authenticated successfully as client.");

            // ... use sslStream for communication ...

            sslStream.Close();
            client.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }

    public static bool ValidateServerCertificate(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        // In a production environment, you should have a more robust certificate validation logic.
        // For this example, we'll allow any certificate.
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine($"Certificate error: {sslPolicyErrors}");
        return false;
    }
}