dotnet/MQTTnet

Connection error when connecting to a Broker through an SSH local forwarded port

mauroa opened this issue · 1 comments

Describe the bug

I'm trying to connect an MQTT client running on Windows, to an MQTT broker running on Mac (both using MQTTnet). To do so, I'm using SSH.NET to establish and SSH connection and I'm also starting a local forwarded port to localhost and the port where the Broker on the Mac is listening.

When I try connecting the client, I receive a SocketException saying the connection has been refused.

Which component is your bug related to?

  • Client

To Reproduce

Steps to reproduce the behavior:

  1. Using MQTTnet version 4.3.7.1207
  2. Using SSH.NET version 2024.0.0
  3. Run this code:

Client Code:

var factory = new MqttFactory();
var mqttVersion = MqttProtocolVersion.V311;
var remotePort = 45555; //Port where the Broker on the Mac will be listening

await ConnectSshAsync(remotePort);
await ConnectRemoteClientAsync(factory, mqttVersion, remotePort);
Console.Read();

async Task ConnectSshAsync(int remotePort)
{
    var host = ""; //This is the Mac IP address
    var username = ""; //This is the Mac user name
    var password = ""; //This is the Mac user password
    var sshClient = new SshClient(host, username, password);

    await sshClient.ConnectAsync(CancellationToken.None);

    //This means that the connection to localhost in the remote port, should be tunneled to the remote host via the forwarded port
    var forwardedPort = new ForwardedPortLocal(IPAddress.Loopback.ToString(), (uint)remotePort, IPAddress.Loopback.ToString(), (uint)remotePort);

    sshClient.AddForwardedPort(forwardedPort);
    forwardedPort.Start();
}

async Task ConnectRemoteClientAsync(MqttFactory factory, MqttProtocolVersion mqttVersion, int remotePort)
{
    var address = IPAddress.Loopback;
    var client1 = factory.CreateMqttClient();
    var client1Id = "TestClient1";
    var connectOptions1 = factory
        .CreateClientOptionsBuilder()
        .WithEndPoint(new IPEndPoint(address, remotePort))
        .WithClientId(client1Id)
        .WithProtocolVersion(mqttVersion)
        .WithCleanStart()
        .WithNoKeepAlive()
        .Build();

    var connection1 = await client1.ConnectAsync(connectOptions1, CancellationToken.None);
}

Server Code:

var factory = new MqttFactory();
var port= 45555;
var serverOptions = factory
    .CreateServerOptionsBuilder()
    .WithDefaultEndpoint()
    .WithDefaultEndpointPort(port)
    .WithDefaultEndpointReuseAddress()
    .Build();
var server = factory.CreateMqttServer(serverOptions);

await server.StartAsync();
  1. See error.

Image

  1. Expected behavior

The connection should be successful

It was a problem on my end, it works now