Sample code for 30+ languages & platforms
Swift

Enumerate Active SSH Channel Numbers

See more SSH Examples

Demonstrates the Chilkat Ssh.GetChannelNumber method, which returns the channel number at a zero-based enumeration index in the active channel collection. The only argument is the index — an enumeration position, not itself a channel number. Valid indexes run from 0 through NumOpenChannels - 1, and out-of-range indexes return -1.

Background: One SSH connection can carry many simultaneous channels, and this method lets you walk the live set rather than tracking every channel number yourself. The index-versus-channel-number distinction is the key point: index 0 is simply the first channel in the collection and may well be channel number 3. As channels open and close the enumeration shifts, so treat an index as valid only for the moment you read it.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Demonstrates the Ssh.GetChannelNumber method, which returns the channel number at a
    //  zero-based enumeration index in the active channel collection.  The only argument is the
    //  index, which is an enumeration position and not itself a channel number.

    let ssh = CkoSsh()!

    var sshPort: Int = 22
    success = ssh.connect(hostname: "ssh.example.com", port: sshPort)
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    var password: String? = "mySshPassword"

    success = ssh.authenticatePw(login: "mySshLogin", password: password)
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    //  Open a couple of channels so the collection has more than one entry.
    var channelA: Int = ssh.openSessionChannel().intValue
    if channelA < 0 {
        print("\(ssh.lastErrorText!)")
        return
    }

    var channelB: Int = ssh.openSessionChannel().intValue
    if channelB < 0 {
        print("\(ssh.lastErrorText!)")
        return
    }

    //  Enumerate the active channels.  Valid indexes are 0 through NumOpenChannels - 1.
    var n: Int = ssh.numOpenChannels.intValue
    print("Open channels: \(n)")
    var i: Int
    for i = 0; i <= n - 1; i++ {
        var chNum: Int = ssh.getChannelNumber(index: i).intValue
        print("Index \(i) is channel number \(chNum)")
    }

    ssh.disconnect()

}