MODBUS_NEW_TCP_PI(3)

๐Ÿ“ฆ
version 3.1.6 ยท 3 versions
, in debian bookworm

๐Ÿ’– MODBUS_NEW_TCP_PI ๐Ÿ’–

okay bestie, welcome to the libmodbus manual, section 3, and today's main character is modbus_new_tcp_pi โ€” she's giving TCP Protocol Independent energy and honestly? obsessed. โœจ


๐ŸŒธ NAME ๐ŸŒธ

modbus_new_tcp_pi โ€” create a libmodbus context for TCP Protocol Independent


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

modbus_t *modbus_new_tcp_pi(const char *node, const char *service);

๐Ÿ’… DESCRIPTION ๐Ÿ’…

so the modbus_new_tcp_pi() function is gonna allocate and initialize a modbus_t structure so you can talk to a Modbus TCP IPv4 or IPv6 server. like, she sets you up. she's the wingwoman. ๐Ÿซถ

the node argument is the host name or IP address of the host you're connecting to โ€” for example "192.168.0.5", "::1" or "server.com". and plot twist: you can pass a NULL value to listen on any addresses in server mode. versatile queen. ๐Ÿ‘‘

the service argument is the service name / port number you're connecting to. want the default Modbus port? use the string "502". and ngl, on many Unix systems it's lowkey convenient to use a port number greater than or equal to 1024 because then you don't need administrator privileges โ€” no sudo moment required. ๐Ÿ™ˆ


๐ŸŒˆ RETURN VALUE ๐ŸŒˆ

if it slays, the function returns a pointer to a modbus_t structure. if it does not slay, it returns NULL and sets errno to one of the values defined below. bestie. ๐Ÿ˜ญ


โญ ERRORS โญ

  • EINVAL โ€” the node string is empty or has been truncated. or the service string is empty or has been truncated. basically somebody sent an empty text message and we're all confused. ๐Ÿ’€
  • ENOMEM โ€” out of memory. possibly the application is hitting its memory limit and/or the whole system is running out of memory. she's running on fumes, fr fr. ๐Ÿ˜ฎโ€๐Ÿ’จ

๐ŸŽ€ EXAMPLE ๐ŸŽ€

modbus_t *ctx;

ctx = modbus_new_tcp_pi("::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;
}

look at that. clean. iconic. she ate. ๐Ÿ”ฅ


๐Ÿ‘‘ SEE ALSO ๐Ÿ‘‘

go read them, they're all part of the friend group. ๐Ÿงš


๐Ÿ’œ AUTHORS ๐Ÿ’œ

the libmodbus documentation was written by Stรฉphane Raimbault <stephane.raimbault@gmail.com> โ€” thank you king, we love a documentation legend. ๐Ÿซก


and that's the whole page, bestie! libmodbus v3.1.6, dated 11/17/2025. now go forth and create contexts responsibly. mwah! ๐Ÿ’‹โœจ
๐Ÿ“ฆ where this page comes from