Skip to content

Modbus TCP Connection Refused — Complete Guide

DodaTech Updated 2026-06-26 1 min read

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

The Problem

Modbus TCP connection to a slave device on port 502 is refused.

Quick Fix

Wrong

modbus_new_tcp('192.168.1.100', 502);  # No connect call shown
Connection refused — firewall or slave not listening.
#include <modbus/modbus.h>

int connect_modbus_tcp() {
  modbus_t *ctx = modbus_new_tcp('192.168.1.100', 502);
  if (ctx == NULL) {
    fprintf(stderr, 'Unable to allocate context\n');
    return -1;
  }
  
  // Set timeout
  modbus_set_timeout(ctx, 5, 0);  // 5 seconds
  
  // Connect
  if (modbus_connect(ctx) == -1) {
    fprintf(stderr, 'TCP connection failed: %s\n',
            modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
  }
  
  printf('Connected to Modbus TCP slave\n');
  
  // Read data
  uint16_t regs[10];
  int rc = modbus_read_registers(ctx, 0, 10, regs);
  if (rc > 0) {
    printf('Read %d registers\n', rc);
  }
  
  modbus_close(ctx);
  modbus_free(ctx);
  return 0;
}

// Test with: nc -zv 192.168.1.100 502
Connected to Modbus TCP slave (or connection error diagnosed).

Prevention

Modbus TCP uses port 502. Check firewall: sudo ufw allow 502/tcp. The slave must have TCP enabled (some only support RTU). Modbus TCP does not have CRC (TCP handles integrity). Transaction ID (first 2 bytes) must match in request/response. Unit ID is less important in TCP but kept for gateway compatibility.

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

FAQ

### Does Modbus TCP require a slave ID?

Unit ID is used when the TCP endpoint is a gateway to RTU slaves. For direct TCP slaves, unit ID is often ignored (set to 0 or 255).

What is the Modbus TCP frame format?

Transaction ID (2 bytes) + Protocol ID (2 bytes, = 0) + Length (2 bytes) + Unit ID (1 byte) + PDU (function + data). No CRC.

Can I use Modbus TCP over the internet?

Not recommended without security. Use Modbus TCP over VPN or TLS tunneling. Plain Modbus TCP has no authentication or encryption.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro