Skip to content

Instantly share code, notes, and snippets.

@jdaigle
Created January 15, 2025 00:33
Show Gist options
  • Save jdaigle/5094f5d817c166b2124870924452ffc2 to your computer and use it in GitHub Desktop.
Save jdaigle/5094f5d817c166b2124870924452ffc2 to your computer and use it in GitHub Desktop.
Test TCP and SSL Stream
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp1;
public class Program
{
public static async Task Main(string[] args)
{
var cancellationToken = new TaskCompletionSource<bool>();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using var client = new TcpClient();
try
{
var task = client.ConnectAsync(args[0], int.Parse(args[1]));
using (cts.Token.Register(() => cancellationToken.TrySetResult(true)))
{
if (task != await Task.WhenAny(task, cancellationToken.Task))
{
throw new Exception($"Unable to connect to {args[0]}:{args[1]} in after timeout");
}
}
using (var ns = new SslStream(client.GetStream(), leaveInnerStreamOpen: false, userCertificateValidationCallback: HandleCertificateValidation))
{
await ns.AuthenticateAsClientAsync(args[0]);
}
}
finally
{
client.Close();
}
}
private static bool HandleCertificateValidation(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslpolicyerrors)
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment