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.
Right
#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
← Previous
Modbus TCP Server Not Responding to Requests
Next →
MongoDB Aggregation $bucket Boundary Not Working Fix
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro