MODBUS_NEW_TCP(3)

πŸ“¦
version 3.1.6 Β· 3 versions
, in debian bookworm

πŸ’– 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