Sample code for 30+ languages & platforms
Zig

Upgrade a Plain TCP Connection to TLS

See more Socket/SSL/TLS Examples

Demonstrates Socket.ConvertToSsl, which upgrades an already-connected plain TCP socket to TLS by performing a client-side TLS handshake over the existing connection.

Background. This supports STARTTLS-style upgrades, where a protocol begins in plaintext and switches to TLS at a defined point. Perform the protocol-specific negotiation first, then call ConvertToSsl.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const socket = try chilkat.Socket.init();
    defer socket.deinit();

    // Connect as plain TCP (no TLS yet).
    const b_tls = false;
    const max_wait_ms = 5000;
    socket.connect("example.com", 5000, b_tls, max_wait_ms) catch {
        std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
        return;
    };

    // At the point where the application protocol permits a STARTTLS-style upgrade, perform any required
    // negotiation, then upgrade the existing connection to TLS with a client-side handshake.
    socket.convertToSsl() catch {
        std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Connection upgraded to TLS.\n", .{});
}