diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 7b15e99f3d..c7db4672ad 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -227,6 +227,16 @@ bool isPrivateIpAddress(const IPAddress &ip) } return false; } + +std::pair parseHostAndPort(std::string address, uint16_t port = 0) +{ + const size_t delimIndex = address.find_first_of(':'); + if (delimIndex > 0) { + port = std::stoul(address.substr(delimIndex + 1, address.length())); + address.resize(delimIndex); + } + return std::make_pair(std::move(address), port); +} } // namespace void MQTT::mqttCallback(char *topic, byte *payload, unsigned int length) @@ -302,7 +312,8 @@ MQTT::MQTT() : concurrency::OSThread("mqtt"), mqttQueue(MAX_MQTT_QUEUE) } IPAddress ip; - isMqttServerAddressPrivate = ip.fromString(moduleConfig.mqtt.address) && isPrivateIpAddress(ip); + isMqttServerAddressPrivate = + ip.fromString(parseHostAndPort(moduleConfig.mqtt.address).first.c_str()) && isPrivateIpAddress(ip); #if HAS_NETWORKING if (!moduleConfig.mqtt.proxy_to_client_enabled) @@ -418,14 +429,9 @@ void MQTT::reconnect() pubSub.setClient(mqttClient); #endif - String server = String(serverAddr); - int delimIndex = server.indexOf(':'); - if (delimIndex > 0) { - String port = server.substring(delimIndex + 1, server.length()); - server[delimIndex] = 0; - serverPort = port.toInt(); - serverAddr = server.c_str(); - } + std::pair hostAndPort = parseHostAndPort(serverAddr, serverPort); + serverAddr = hostAndPort.first.c_str(); + serverPort = hostAndPort.second; pubSub.setServer(serverAddr, serverPort); pubSub.setBufferSize(512);