MODBUS_NEW_TCP(3)
π MODBUS_NEW_TCP(3) π
okay bestie, we're in the libmodbus Manual, section 3, and today's main character is modbus_new_tcp(3) β¨
πΈ NAME πΈ
modbus_new_tcp β create a libmodbus context for TCP/IPv4, no cap π«Ά
β¨ SYNOPSIS β¨
modbus_t *modbus_new_tcp(const char *ip, int port);
π¦ DESCRIPTION π¦
So the modbus_new_tcp() function shall allocate and initialize a modbus_t structure, and it's literally built so you can talk to a Modbus TCP IPv4 server π
The ip argument is the IP address of the server your client wants to establish a connection with. And get this β a NULL value can be used to listen on any addresses in server mode. iconic behaviour honestly.
The port argument is the TCP port to use. Set the port to MODBUS_TCP_DEFAULT_PORT if you want the default one, which is 502 β and fr fr, it's convenient to use a port number greater than or equal to 1024 because then you don't need administrator privileges. no sudo era, we love to see it π
π RETURN VALUE π
The function shall return a pointer to a modbus_t structure if it's successful π Otherwise it shall return NULL and set errno to one of the values defined below. so like, always check bestie, always check π
π ERRORS π
EINVALβ an invalid IP address was given. like girl what even is that address πENOMEMβ out of memory. Possibly, the application hits its memory limit and/or the whole system is running out of memory. it's giving stressed π
π EXAMPLE π
modbus_t *ctx;
ctx = modbus_new_tcp("127.0.0.1", 1502);
if (ctx == NULL) {
fprintf(stderr, "Unable to allocate libmodbus context\n");
return -1;
}
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
see how it checks for NULL and cleans up with modbus_free(ctx)? that's the self-care we're talking about π
β¨
π SEE ALSO π
π AUTHORS π
The libmodbus documentation was written by StΓ©phane Raimbault <stephane.raimbault@gmail.com> β shoutout to the icon, thank you for your service π«Άπ
and that's a wrap bestie!! this page came to you from libmodbus v3.1.6, dated 11/17/2025. stay connected, stay allocated, and remember to free your context πβ¨π¦
π¦ where this page comes from
- debian bookworm: libmodbus-dev 3.1.6-2.1+deb12u1 Β· LGPL-2.1-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms