I'm having some issues dealing with strings in a small Arduino app. I wonder why this code works:
mqtt.setServer("192.168.1.42", port);
and this code doesn't:
IPAddress ip = MDNS.queryHost(...);
mqtt.setServer(ip.toString().c_str(), port);
Even when strcmp
returns 0 when I compare both:
strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality
I've also tried other alternatives, such as creating a char
array, with no luck:
String ipstr = ip.toString();
char ipchar[ipstr.length() + 1];
ipstr.toCharArray(ipchar, ipstr.length() + 1);
mqtt.setServer(ipchar, port);
All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.
1 Answer 1
PubSubClient::setServer(const char * domain, uint16_t port)
just saves the pointer, it doesn't copy the string (probably because it expects a static string literal).
(Source)
In your case, when ip
goes out of scope, the pointer is no longer valid, so it won't work.
Just use the PubSubClient::setServer(IPAddress ip, uint16_t port)
function instead.
(Source)
Always read the API documentation, most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the header files, which list all functions of the library.
If you still have doubts about what a function does, refer to the actual implementation files.
mqtt.setServer
do? Does it store a pointer reference or does it copy the input string to its own buffers? If you use a constant "192.168.1.42" then that string will be static. WHen you useip.toString().c_str()
, when theip
object is deallocated but.setServer()
still has a reference to thatchar*
, it's become invalid. Where is the library you're using?