Skip to content

Modbus Tcp Client

DodaTech 1 min read

In this tutorial, you'll learn about Modbus TCP Client Connection Refused. We cover key concepts, practical examples, and best practices.

The Problem

Modbus TCP client cannot connect to the Modbus TCP server.

Quick Fix

Wrong

client.connect("192.168.1.100", 502);  // Standard Modbus TCP port```

Connection refused. Modbus TCP server not listening on port 502.


### Right

```cpp
#include <Ethernet.h>
#include <ModbusIP.h>

ModbusIP mb;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  delay(1000);

  // Connect to Modbus TCP server
  mb.connect("192.168.1.100");
  Serial.println("Connected to Modbus server");
}

void loop() {
  // Read holding registers from remote device
  uint16_t values[10];
  mb.readHoldingRegisters(1, 0, 10, values);

  static uint32_t lastRead = 0;
  if (millis() - lastRead > 2000) {
    for (int i = 0; i < 5; i++) {
      Serial.print("Reg ");
      Serial.print(i);
      Serial.print(": ");
      Serial.println(values[i]);
    }
    lastRead = millis();
  }

  mb.task();  // Process incoming messages
}```

Connected to Modbus server Reg 0: 1234 Reg 1: 5678 ...


## Prevention

Modbus TCP uses port 502. The client connects to the server's IP address and sends requests with a 7-byte MBAP header (Transaction ID, Protocol ID=0, Length, Unit ID). Each request/response pair uses a unique Transaction ID. The ModbusIP library handles MBAP header creation automatically. Check firewall: TCP 502 must be open.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

## FAQ

<details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">### Default Modbus TCP port?</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>502 (IANA assigned). Can use alternate ports, but all clients/servers must match.</p>
<h3 id="can-multiple-clients-connect">Can multiple clients connect?</h3><p>Yes. Modbus TCP supports multiple simultaneous client connections (unlike RTU which is single-master). Server handles each connection independently.</p>
<h3 id="is-modbus-tcp-faster-than-rtu">Is Modbus TCP faster than RTU?</h3><p>Yes. No bit-level serialization overhead. No inter-frame delays. Can be 10-100x faster than RTU at equivalent baud rates.</p>
</div></details>

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro