how to use a username and password for mosquitto_new c/c++ mqtt

954 views Asked by At

Hi so I am using linux (ubuntu) and I am using c/c++ with the libmosquitto mqtt library. There is a function called mosquitto_new() that takes the client id, cleas_session and a void object pointer as the arguments. In all the examples I have seen online the void object pointer parameter has been left as NULL meaning that no username or password was required. I did see online that if you want to use a username and password then you change the void pointer object from NULL to a pointer to your username and password.

But I dont understand how that works, because if you had your username and password in the code it kinda defeats the point of having a password.

I know that from testing if you just use the terminal to use the mosquitto mqtt broker then you make a text file that has the username and password and change the .conf file to not allow anonymous users and enable the username and password file. But I am unsure how to do this in c/c++ using the mosquitto library.

So overall if anyone has any idea how to do this I would greatly appreciate the help, I think it is to do with changing the NULL in the mosquitto_new function but am unsure.

Attached is my code for the publisher that I have working atm if it is any help.

#include <iostream>
#include <stdio.h>
#include </home/dave/mosquitto/include/mosquitto.h>

using namespace std;

int main(){
      int rc;
      char message[] = "Hello World testing";
      
      struct mosquitto * mosq;

      mosquitto_lib_init();
      

      mosq = mosquitto_new("publisher-test", true, NULL);

      rc = mosquitto_connect(mosq, "130.246.57.26", 1883, 60); // ip 130.246.57.26
      if(rc != 0){
            printf("Client could not connect to broker! Error Code: %d\n", rc);
            mosquitto_destroy(mosq);
            return -1;
      }
      printf("We are now connected to the broker!\n");

      mosquitto_publish(mosq, NULL, "test/1", sizeof(message), &message , 0, false);

      mosquitto_disconnect(mosq);
      mosquitto_destroy(mosq);

      mosquitto_lib_cleanup();
      return 0;
}

Thanks in advance, Dean

1

There are 1 answers

0
hardillb On

The correct section of the documentation is here which discusses the mosquitto_username_pw_set function which is used to update the mosq struct with the username/password before mosquitto_connect is called.

e.g.

      struct mosquitto * mosq;
      mosquitto_lib_init();

      mosq = mosquitto_new("publisher-test", true, NULL);
      mosquitto_username_pw_set(mosq, "username", "password")

      rc = mosquitto_connect(mosq, "130.246.57.26", 1883, 60);