Search code examples
flutterflutter-dependenciesmqttsocketexceptionandroid-mqtt-client

Exception: SocketException: Failed host lookup: 'tcp://*******:1883' (OS Error: No address associated with hostname, errno = 7)


I am getting the error Exception: SocketException: Failed host lookup: 'tcp://*******:1883' (OS Error: No address associated with hostname, errno = 7) when I use the mqtt5_client library for my flutter project when using a physical android device. When I tried using MQTT with the paho library on android studio using kotlin, I was able to establish connection and publish data. However, when I try using mqtt with flutter instead, I get this failed host lookup error.

I have tried adding permission such as the INTERNET in the manifest file. I used mqtt_client before and then changed yo mqtt5_client with the hopes that I will be able to establish a connection but the problem still exists. I am unsure of what might be causing this issue. Any help will be appreciated.

Below is the code I am using.

import 'package:logger/logger.dart';

import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';

class MQTTClientService {
  late MqttServerClient _client;
  var logger = Logger();

  MQTTClientService(String brokerURL, String clientId, int port) {
    _client = MqttServerClient(brokerURL, clientId);
    _client.port = port;
    _client.logging(on: true);
    _client.onConnected = _onConnected;
    _client.onDisconnected = _onDisconnected;
    _client.onUnsubscribed = _onUnsubscribed;
    _client.onSubscribed = _onSubscribed;
    _client.onSubscribeFail = _onSubscribeFail;
    _client.pongCallback = _pong;
    _client.keepAlivePeriod = 60;
  }

  Future<void> establishConnection() async {
    final connectMessage =
        MqttConnectMessage().startClean().withWillQos(MqttQos.atLeastOnce);

    logger.i('MQTT_LOGS::Mosquitto client connecting....');

    _client.connectionMessage = connectMessage;

    try {
      await _client.connect();
    } catch (e) {
      logger.e('Exception: $e');
      _client.disconnect();
    }

    if (_client.connectionStatus!.state == MqttConnectionState.connected) {
      logger.i('MQTT_LOGS::Mosquitto client connected');
    } else {
      logger.i(
          'MQTT_LOGS::ERROR Mosquitto client connection failed - disconnecting, status is ${_client.connectionStatus}');

      _client.disconnect();
    }
  }

  void subscribeToTopic(String topic) {
     // code to subscribe
  }

  void publishMessage(String topic, String message) {
   // code to publish
  }

  void terminateClientConnection() {
    _client.disconnect();
  }

  void _onConnected() {
    logger.i('MQTT_LOGS:: Connected');
  }

  void _onDisconnected() {
    logger.i('MQTT_LOGS:: Disconnected');
  }

  void _onSubscribed(MqttSubscription subscription) {
    logger.i('MQTT_LOGS:: Subscribed topic: ${subscription.topic}');
  }

  void _onSubscribeFail(MqttSubscription subscription) {
    logger.i('MQTT_LOGS:: Failed to subscribe ${subscription.topic}');
  }

  void _onUnsubscribed(MqttSubscription? subscription) {
    if (subscription != null) {
      logger.i('MQTT_LOGS:: Unsubscribed topic: ${subscription.topic}');
    }
  }

  void _pong() {
    logger.i('MQTT_LOGS:: Ping response client callback invoked');
  }
}

The permissions I am currently using

   <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

Solution

  • From the API Docs (https://pub.dev/documentation/mqtt5_client/latest/mqtt5_server_client/MqttServerClient/MqttServerClient.html)

    MqttServerClient(
    
      String server,
      String clientIdentifier,
      {int maxConnectionAttempts = 3}
    
    )
    

    Initializes a new instance of the MqttServerClient class using the default Mqtt Port. The server hostname to connect to The client identifier to use to connect with

    MqttServerClient(brokerURL, clientId); takes a hostname NOT a URI

    brokerURL should just be the hostname of the broker, not a URI (no tcp:// in the start and :1883 on the end)