SSH.NET icon indicating copy to clipboard operation
SSH.NET copied to clipboard

[Feature Request] Add IsConnected() method to check session status

Open tattdogg opened this issue 6 months ago • 3 comments

The existing IsConnected property does not always reliably reflect the actual state of the SSH session. For example, it may still return true even if the connection has silently dropped due to network issues or server-side timeouts.

It would be helpful to have a method like IsConnected() that actively attempts to communicate with the server (e.g., by sending a keep-alive packet or executing a lightweight command) to verify whether the session is still alive. This would improve robustness in long-running applications and allow developers to handle disconnections more gracefully.

tattdogg avatar Aug 05 '25 07:08 tattdogg

Have you considered using Client.KeepAliveInterval?

Rob-Hague avatar Aug 07 '25 07:08 Rob-Hague

Yes, setting this does simplify things, but there’s still a problem. For example, if the server’s timeout is 10 minutes and KeepAliveInterval is set to 20 minutes, IsConnected will still return true even after 15 minutes, even though the server has already closed the session.

tattdogg avatar Aug 07 '25 08:08 tattdogg

I have this helper right now

private async Task<bool> IsConnectedAsync(CancellationToken cancellationToken)
    {
        if (!_sftpClient.IsConnected)
            return false;

        try
        {
            await _sftpClient.ExistsAsync(".", cancellationToken);
            return true;
        }
        catch (Exception ex) when (ex is SshConnectionException or SocketException)
        {
            // SshConnectionException - Client not connected
            // SshConnectionException - An established connection was aborted by the server
            // SocketException -        An existing connection was forcibly closed by the remote host

            _sftpClient.Disconnect();
            return false;
        }
    }

probably there is more effective way to do that using BaseClient methods (low level)

tattdogg avatar Aug 07 '25 08:08 tattdogg