Do we have a event to notify when ssh connection is broken?

0 votes
asked Mar 25 by wvvlhly5v (120 points)

Do we have a event to notify when ssh connection is broken?

I use the Rebex.Ssh-Lib to establish a ssh-tunnel.
How can I be informed when the tunnel is broken, e.g. wifi is lost?

I try this:

        var ssh = new Rebex.Net.Ssh();
        ssh.Connect(destIp.ToString(), remotePort);
        ssh.Login(..., ...);

        var tunnel = ssh.StartOutgoingTunnel(
            sshLocalhost.ToString(), 0,
            sshLocalhost.ToString(), remotePort);

        Task.Run(async () =>
        {
            while (true)
            {
                await Task.Delay(1000);
                ssh.CheckConnectionState();
                var cs = _ssh.GetConnectionState();
                Console.WriteLine($"Error:{cs.NativeErrorCode} | IsConnected:{cs.Connected}"); 
            }
        });

The output is alway Error:0 | true
How can I reliable check the connectionstate?

1 Answer

0 votes
answered Mar 25 by Lukas Pokorny (126,870 points)

If no data is transferred over the TCP connection, ssh.CheckConnectionState method might be unable to detect that the connection has been lost, because the operating system's TCP/IP subsystem is not aware of that yet. To work around this, call ssh.KeepAlive() method periodically (such as every 30 seconds or so) in addition to your current code.

Also, there is no need to call both CheckConnectionState() and GetConnectionState() - these methods are equivalent internally, so either use one or the other.

...