| 1 | # modbus_new_tcp_pi |
| 2 | |
| 3 | ## Name |
| 4 | |
| 5 | modbus_new_tcp_pi - create a libmodbus context for TCP Protocol Independent |
| 6 | |
| 7 | ## Synopsis |
| 8 | |
| 9 | ```c |
| 10 | modbus_t *modbus_new_tcp_pi(const char *node, const char *service); |
| 11 | ``` |
| 12 | |
| 13 | ## Description |
| 14 | |
| 15 | The *modbus_new_tcp_pi()* function shall allocate and initialize a *modbus_t* |
| 16 | structure to communicate with a Modbus TCP IPv4 or IPv6 server. |
| 17 | |
| 18 | The `node` argument specifies the host name or IP address of the host to connect |
| 19 | to, eg. "192.168.0.5" , "::1" or "server.com". A NULL value can be used to |
| 20 | listen any addresses in server mode. |
| 21 | |
| 22 | The `service` argument is the service name/port number to connect to. To use the |
| 23 | default Modbus port, you can provide a NULL value or the string "502". On many |
| 24 | Unix systems, it's convenient to use a port number greater than or equal to 1024 |
| 25 | because it's not necessary to have administrator privileges. |
| 26 | |
| 27 | :octicons-tag-24: v3.1.8 handles NULL value for `service` (no *EINVAL* error). |
| 28 | |
| 29 | ## Return value |
| 30 | |
| 31 | The function shall return a pointer to a *modbus_t* structure if |
| 32 | successful. Otherwise it shall return NULL and set errno to one of the values |
| 33 | defined below. |
| 34 | |
| 35 | ## Errors |
| 36 | |
| 37 | - *ENOMEM*, out of memory. Possibly, the application hits its memory limit |
| 38 | and/or whole system is running out of memory. |
| 39 | |
| 40 | ## Example |
| 41 | |
| 42 | ```c |
| 43 | modbus_t *ctx; |
| 44 | |
| 45 | ctx = modbus_new_tcp_pi("::1", "502"); |
| 46 | if (ctx == NULL) { |
| 47 | fprintf(stderr, "Unable to allocate libmodbus context\n"); |
| 48 | return -1; |
| 49 | } |
| 50 | |
| 51 | if (modbus_connect(ctx) == -1) { |
| 52 | fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno)); |
| 53 | modbus_free(ctx); |
| 54 | return -1; |
| 55 | } |
| 56 | ``` |
| 57 | |
| 58 | ## See also |
| 59 | |
| 60 | - [modbus_new_tcp](modbus_new_tcp.md) |
| 61 | - [modbus_tcp_pi_listen](modbus_tcp_pi_listen.md) |
| 62 | - [modbus_free](modbus_free.md) |