peropata
peropata

Reputation: 43

C# SSH tunnel Postgres database connection

I am trying to connect to the Postgres database on remote server through SSH tunnel. I am using SSH.NET and Npgsql library. Here is my example code:

using (var client = new SshClient("210.130.90.110", "root", "pasword"))
{
    client.Connect();

    if (!client.IsConnected)
    {
        // Display error
        Console.WriteLine("Client not connected!");
    }
    else
    {
        Console.WriteLine("Client connected!");
    }

    var port = new ForwardedPortLocal("127.0.0.1", 15432, "210.130.90.110", 5432);
    client.AddForwardedPort(port);

    port.Start();

    using (var conn = new NpgsqlConnection("Server=127.0.0.1;Database=dbname;Port=15432;User Id=dbuser;Password=dbpassword;"))
    {
        conn.Open();
    }

    port.Stop();
    client.Disconnect();
}

After code execution I get:

Npgsql.NpgsqlException: 'Exception while reading from stream' EndOfStreamException: Attempted to read past the end of the stream.

I am able to connect to database using DBeaver.

Upvotes: 3

Views: 6417

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202262

The remote end of the port forwarding is resolved on the server. So you need set the IP address/hostname in a way that works, as it you are connecting from the server itself.

The database probably listens on the localhost interface only. Not on the public IP address (if it were, you possibly would not need the port forwarding in the first place).

Additionally, it is not a good idea to hard-code the local forwarded port. You cannot know, if that port is not already occupied by another application. Let the system choose any free local port.

var port = new ForwardedPortLocal("127.0.0.1", "127.0.0.1", 5432);
client.AddForwardedPort(port);
port.Start();

string connString =
    $"Server={port.BoundHost};Database=dbname;Port={port.BoundPort};" +
     "User Id=dbuser;Password=dbpassword;";

using (var conn = new NpgsqlConnection(connString))
{
    conn.Open();
}

Related: MySQL port forwading in SSH.NET - An attempt was made to access a socket in a way forbidden by its access permissions

Upvotes: 3

Related Questions