Rewrite and extend functions to manipulate float values
[libmodbus.git] / src / modbus-tcp.c
blob00de11cd0dcd84e1a7ebade84ab8ff2fe2b0b499
1 /*
2 * Copyright © 2001-2013 Stéphane Raimbault <stephane.raimbault@gmail.com>
4 * SPDX-License-Identifier: LGPL-2.1+
5 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <errno.h>
11 #ifndef _MSC_VER
12 #include <unistd.h>
13 #endif
14 #include <signal.h>
15 #include <sys/types.h>
17 #if defined(_WIN32)
18 # define OS_WIN32
19 /* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later.
20 * minwg32 headers check WINVER before allowing the use of these */
21 # ifndef WINVER
22 # define WINVER 0x0501
23 # endif
24 /* Already set in modbus-tcp.h but it seems order matters in VS2005 */
25 # include <winsock2.h>
26 # include <ws2tcpip.h>
27 # define SHUT_RDWR 2
28 # define close closesocket
29 #else
30 # include <sys/socket.h>
31 # include <sys/ioctl.h>
33 #if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ < 5)
34 # define OS_BSD
35 # include <netinet/in_systm.h>
36 #endif
38 # include <netinet/in.h>
39 # include <netinet/ip.h>
40 # include <netinet/tcp.h>
41 # include <arpa/inet.h>
42 # include <netdb.h>
43 #endif
45 #if !defined(MSG_NOSIGNAL)
46 #define MSG_NOSIGNAL 0
47 #endif
49 #include "modbus-private.h"
51 #include "modbus-tcp.h"
52 #include "modbus-tcp-private.h"
54 #ifdef OS_WIN32
55 static int _modbus_tcp_init_win32(void)
57 /* Initialise Windows Socket API */
58 WSADATA wsaData;
60 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
61 fprintf(stderr, "WSAStartup() returned error code %d\n",
62 (unsigned int)GetLastError());
63 errno = EIO;
64 return -1;
66 return 0;
68 #endif
70 static int _modbus_set_slave(modbus_t *ctx, int slave)
72 /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */
73 if (slave >= 0 && slave <= 247) {
74 ctx->slave = slave;
75 } else if (slave == MODBUS_TCP_SLAVE) {
76 /* The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to
77 * restore the default value. */
78 ctx->slave = slave;
79 } else {
80 errno = EINVAL;
81 return -1;
84 return 0;
87 /* Builds a TCP request header */
88 static int _modbus_tcp_build_request_basis(modbus_t *ctx, int function,
89 int addr, int nb,
90 uint8_t *req)
92 modbus_tcp_t *ctx_tcp = ctx->backend_data;
94 /* Increase transaction ID */
95 if (ctx_tcp->t_id < UINT16_MAX)
96 ctx_tcp->t_id++;
97 else
98 ctx_tcp->t_id = 0;
99 req[0] = ctx_tcp->t_id >> 8;
100 req[1] = ctx_tcp->t_id & 0x00ff;
102 /* Protocol Modbus */
103 req[2] = 0;
104 req[3] = 0;
106 /* Length will be defined later by set_req_length_tcp at offsets 4
107 and 5 */
109 req[6] = ctx->slave;
110 req[7] = function;
111 req[8] = addr >> 8;
112 req[9] = addr & 0x00ff;
113 req[10] = nb >> 8;
114 req[11] = nb & 0x00ff;
116 return _MODBUS_TCP_PRESET_REQ_LENGTH;
119 /* Builds a TCP response header */
120 static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp)
122 /* Extract from MODBUS Messaging on TCP/IP Implementation
123 Guide V1.0b (page 23/46):
124 The transaction identifier is used to associate the future
125 response with the request. */
126 rsp[0] = sft->t_id >> 8;
127 rsp[1] = sft->t_id & 0x00ff;
129 /* Protocol Modbus */
130 rsp[2] = 0;
131 rsp[3] = 0;
133 /* Length will be set later by send_msg (4 and 5) */
135 /* The slave ID is copied from the indication */
136 rsp[6] = sft->slave;
137 rsp[7] = sft->function;
139 return _MODBUS_TCP_PRESET_RSP_LENGTH;
143 static int _modbus_tcp_prepare_response_tid(const uint8_t *req, int *req_length)
145 return (req[0] << 8) + req[1];
148 static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length)
150 /* Substract the header length to the message length */
151 int mbap_length = req_length - 6;
153 req[4] = mbap_length >> 8;
154 req[5] = mbap_length & 0x00FF;
156 return req_length;
159 static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length)
161 /* MSG_NOSIGNAL
162 Requests not to send SIGPIPE on errors on stream oriented
163 sockets when the other end breaks the connection. The EPIPE
164 error is still returned. */
165 return send(ctx->s, (const char *)req, req_length, MSG_NOSIGNAL);
168 static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req) {
169 return _modbus_receive_msg(ctx, req, MSG_INDICATION);
172 static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length) {
173 return recv(ctx->s, (char *)rsp, rsp_length, 0);
176 static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length)
178 return msg_length;
181 static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx, const uint8_t *req,
182 const uint8_t *rsp, int rsp_length)
184 /* Check transaction ID */
185 if (req[0] != rsp[0] || req[1] != rsp[1]) {
186 if (ctx->debug) {
187 fprintf(stderr, "Invalid transaction ID received 0x%X (not 0x%X)\n",
188 (rsp[0] << 8) + rsp[1], (req[0] << 8) + req[1]);
190 errno = EMBBADDATA;
191 return -1;
194 /* Check protocol ID */
195 if (rsp[2] != 0x0 && rsp[3] != 0x0) {
196 if (ctx->debug) {
197 fprintf(stderr, "Invalid protocol ID received 0x%X (not 0x0)\n",
198 (rsp[2] << 8) + rsp[3]);
200 errno = EMBBADDATA;
201 return -1;
204 return 0;
207 static int _modbus_tcp_set_ipv4_options(int s)
209 int rc;
210 int option;
212 /* Set the TCP no delay flag */
213 /* SOL_TCP = IPPROTO_TCP */
214 option = 1;
215 rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
216 (const void *)&option, sizeof(int));
217 if (rc == -1) {
218 return -1;
221 /* If the OS does not offer SOCK_NONBLOCK, fall back to setting FIONBIO to
222 * make sockets non-blocking */
223 /* Do not care about the return value, this is optional */
224 option = 1;
225 #if !defined(SOCK_NONBLOCK) && defined(FIONBIO)
226 #ifdef OS_WIN32
228 /* Setting FIONBIO expects an unsigned long according to MSDN */
229 u_long loption = 1;
230 ioctlsocket(s, FIONBIO, &loption);
232 #else
233 ioctl(s, FIONBIO, &option);
234 #endif
235 #endif
237 #ifndef OS_WIN32
239 * Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
240 * necessary to workaround that problem.
242 /* Set the IP low delay option */
243 option = IPTOS_LOWDELAY;
244 rc = setsockopt(s, IPPROTO_IP, IP_TOS,
245 (const void *)&option, sizeof(int));
246 if (rc == -1) {
247 return -1;
249 #endif
251 return 0;
254 static int _connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen,
255 const struct timeval *ro_tv)
257 int rc = connect(sockfd, addr, addrlen);
259 #ifdef OS_WIN32
260 int wsaError = 0;
261 if (rc == -1) {
262 wsaError = WSAGetLastError();
265 if (wsaError == WSAEWOULDBLOCK || wsaError == WSAEINPROGRESS) {
266 #else
267 if (rc == -1 && errno == EINPROGRESS) {
268 #endif
269 fd_set wset;
270 int optval;
271 socklen_t optlen = sizeof(optval);
272 struct timeval tv = *ro_tv;
274 /* Wait to be available in writing */
275 FD_ZERO(&wset);
276 FD_SET(sockfd, &wset);
277 rc = select(sockfd + 1, NULL, &wset, NULL, &tv);
278 if (rc <= 0) {
279 /* Timeout or fail */
280 return -1;
283 /* The connection is established if SO_ERROR and optval are set to 0 */
284 rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&optval, &optlen);
285 if (rc == 0 && optval == 0) {
286 return 0;
287 } else {
288 errno = ECONNREFUSED;
289 return -1;
292 return rc;
295 /* Establishes a modbus TCP connection with a Modbus server. */
296 static int _modbus_tcp_connect(modbus_t *ctx)
298 int rc;
299 /* Specialized version of sockaddr for Internet socket address (same size) */
300 struct sockaddr_in addr;
301 modbus_tcp_t *ctx_tcp = ctx->backend_data;
302 int flags = SOCK_STREAM;
304 #ifdef OS_WIN32
305 if (_modbus_tcp_init_win32() == -1) {
306 return -1;
308 #endif
310 #ifdef SOCK_CLOEXEC
311 flags |= SOCK_CLOEXEC;
312 #endif
314 #ifdef SOCK_NONBLOCK
315 flags |= SOCK_NONBLOCK;
316 #endif
318 ctx->s = socket(PF_INET, flags, 0);
319 if (ctx->s == -1) {
320 return -1;
323 rc = _modbus_tcp_set_ipv4_options(ctx->s);
324 if (rc == -1) {
325 close(ctx->s);
326 ctx->s = -1;
327 return -1;
330 if (ctx->debug) {
331 printf("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port);
334 addr.sin_family = AF_INET;
335 addr.sin_port = htons(ctx_tcp->port);
336 addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
337 rc = _connect(ctx->s, (struct sockaddr *)&addr, sizeof(addr), &ctx->response_timeout);
338 if (rc == -1) {
339 close(ctx->s);
340 ctx->s = -1;
341 return -1;
344 return 0;
347 /* Establishes a modbus TCP PI connection with a Modbus server. */
348 static int _modbus_tcp_pi_connect(modbus_t *ctx)
350 int rc;
351 struct addrinfo *ai_list;
352 struct addrinfo *ai_ptr;
353 struct addrinfo ai_hints;
354 modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
356 #ifdef OS_WIN32
357 if (_modbus_tcp_init_win32() == -1) {
358 return -1;
360 #endif
362 memset(&ai_hints, 0, sizeof(ai_hints));
363 #ifdef AI_ADDRCONFIG
364 ai_hints.ai_flags |= AI_ADDRCONFIG;
365 #endif
366 ai_hints.ai_family = AF_UNSPEC;
367 ai_hints.ai_socktype = SOCK_STREAM;
368 ai_hints.ai_addr = NULL;
369 ai_hints.ai_canonname = NULL;
370 ai_hints.ai_next = NULL;
372 ai_list = NULL;
373 rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service,
374 &ai_hints, &ai_list);
375 if (rc != 0) {
376 if (ctx->debug) {
377 fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
379 errno = ECONNREFUSED;
380 return -1;
383 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
384 int flags = ai_ptr->ai_socktype;
385 int s;
387 #ifdef SOCK_CLOEXEC
388 flags |= SOCK_CLOEXEC;
389 #endif
391 #ifdef SOCK_NONBLOCK
392 flags |= SOCK_NONBLOCK;
393 #endif
395 s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
396 if (s < 0)
397 continue;
399 if (ai_ptr->ai_family == AF_INET)
400 _modbus_tcp_set_ipv4_options(s);
402 if (ctx->debug) {
403 printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
406 rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
407 if (rc == -1) {
408 close(s);
409 continue;
412 ctx->s = s;
413 break;
416 freeaddrinfo(ai_list);
418 if (ctx->s < 0) {
419 return -1;
422 return 0;
425 /* Closes the network connection and socket in TCP mode */
426 static void _modbus_tcp_close(modbus_t *ctx)
428 if (ctx->s != -1) {
429 shutdown(ctx->s, SHUT_RDWR);
430 close(ctx->s);
431 ctx->s = -1;
435 static int _modbus_tcp_flush(modbus_t *ctx)
437 int rc;
438 int rc_sum = 0;
440 do {
441 /* Extract the garbage from the socket */
442 char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
443 #ifndef OS_WIN32
444 rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
445 #else
446 /* On Win32, it's a bit more complicated to not wait */
447 fd_set rset;
448 struct timeval tv;
450 tv.tv_sec = 0;
451 tv.tv_usec = 0;
452 FD_ZERO(&rset);
453 FD_SET(ctx->s, &rset);
454 rc = select(ctx->s+1, &rset, NULL, NULL, &tv);
455 if (rc == -1) {
456 return -1;
459 if (rc == 1) {
460 /* There is data to flush */
461 rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0);
463 #endif
464 if (rc > 0) {
465 rc_sum += rc;
467 } while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
469 return rc_sum;
472 /* Listens for any request from one or many modbus masters in TCP */
473 int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
475 int new_s;
476 int enable;
477 struct sockaddr_in addr;
478 modbus_tcp_t *ctx_tcp;
480 if (ctx == NULL) {
481 errno = EINVAL;
482 return -1;
485 ctx_tcp = ctx->backend_data;
487 #ifdef OS_WIN32
488 if (_modbus_tcp_init_win32() == -1) {
489 return -1;
491 #endif
493 new_s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
494 if (new_s == -1) {
495 return -1;
498 enable = 1;
499 if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR,
500 (char *)&enable, sizeof(enable)) == -1) {
501 close(new_s);
502 return -1;
505 memset(&addr, 0, sizeof(addr));
506 addr.sin_family = AF_INET;
507 /* If the modbus port is < to 1024, we need the setuid root. */
508 addr.sin_port = htons(ctx_tcp->port);
509 if (ctx_tcp->ip[0] == '0') {
510 /* Listen any addresses */
511 addr.sin_addr.s_addr = htonl(INADDR_ANY);
512 } else {
513 /* Listen only specified IP address */
514 addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
516 if (bind(new_s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
517 close(new_s);
518 return -1;
521 if (listen(new_s, nb_connection) == -1) {
522 close(new_s);
523 return -1;
526 return new_s;
529 int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
531 int rc;
532 struct addrinfo *ai_list;
533 struct addrinfo *ai_ptr;
534 struct addrinfo ai_hints;
535 const char *node;
536 const char *service;
537 int new_s;
538 modbus_tcp_pi_t *ctx_tcp_pi;
540 if (ctx == NULL) {
541 errno = EINVAL;
542 return -1;
545 ctx_tcp_pi = ctx->backend_data;
547 #ifdef OS_WIN32
548 if (_modbus_tcp_init_win32() == -1) {
549 return -1;
551 #endif
553 if (ctx_tcp_pi->node[0] == 0) {
554 node = NULL; /* == any */
555 } else {
556 node = ctx_tcp_pi->node;
559 if (ctx_tcp_pi->service[0] == 0) {
560 service = "502";
561 } else {
562 service = ctx_tcp_pi->service;
565 memset(&ai_hints, 0, sizeof (ai_hints));
566 /* If node is not NULL, than the AI_PASSIVE flag is ignored. */
567 ai_hints.ai_flags |= AI_PASSIVE;
568 #ifdef AI_ADDRCONFIG
569 ai_hints.ai_flags |= AI_ADDRCONFIG;
570 #endif
571 ai_hints.ai_family = AF_UNSPEC;
572 ai_hints.ai_socktype = SOCK_STREAM;
573 ai_hints.ai_addr = NULL;
574 ai_hints.ai_canonname = NULL;
575 ai_hints.ai_next = NULL;
577 ai_list = NULL;
578 rc = getaddrinfo(node, service, &ai_hints, &ai_list);
579 if (rc != 0) {
580 if (ctx->debug) {
581 fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
583 errno = ECONNREFUSED;
584 return -1;
587 new_s = -1;
588 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
589 int s;
591 s = socket(ai_ptr->ai_family, ai_ptr->ai_socktype,
592 ai_ptr->ai_protocol);
593 if (s < 0) {
594 if (ctx->debug) {
595 perror("socket");
597 continue;
598 } else {
599 int enable = 1;
600 rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
601 (void *)&enable, sizeof (enable));
602 if (rc != 0) {
603 close(s);
604 if (ctx->debug) {
605 perror("setsockopt");
607 continue;
611 rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
612 if (rc != 0) {
613 close(s);
614 if (ctx->debug) {
615 perror("bind");
617 continue;
620 rc = listen(s, nb_connection);
621 if (rc != 0) {
622 close(s);
623 if (ctx->debug) {
624 perror("listen");
626 continue;
629 new_s = s;
630 break;
632 freeaddrinfo(ai_list);
634 if (new_s < 0) {
635 return -1;
638 return new_s;
641 int modbus_tcp_accept(modbus_t *ctx, int *s)
643 struct sockaddr_in addr;
644 socklen_t addrlen;
646 if (ctx == NULL) {
647 errno = EINVAL;
648 return -1;
651 addrlen = sizeof(addr);
652 #ifdef HAVE_ACCEPT4
653 /* Inherit socket flags and use accept4 call */
654 ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
655 #else
656 ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
657 #endif
659 if (ctx->s == -1) {
660 close(*s);
661 *s = -1;
662 return -1;
665 if (ctx->debug) {
666 printf("The client connection from %s is accepted\n",
667 inet_ntoa(addr.sin_addr));
670 return ctx->s;
673 int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
675 struct sockaddr_storage addr;
676 socklen_t addrlen;
678 if (ctx == NULL) {
679 errno = EINVAL;
680 return -1;
683 addrlen = sizeof(addr);
684 #ifdef HAVE_ACCEPT4
685 /* Inherit socket flags and use accept4 call */
686 ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
687 #else
688 ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
689 #endif
690 if (ctx->s == -1) {
691 close(*s);
692 *s = -1;
695 if (ctx->debug) {
696 printf("The client connection is accepted.\n");
699 return ctx->s;
702 static int _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
704 int s_rc;
705 while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) {
706 if (errno == EINTR) {
707 if (ctx->debug) {
708 fprintf(stderr, "A non blocked signal was caught\n");
710 /* Necessary after an error */
711 FD_ZERO(rset);
712 FD_SET(ctx->s, rset);
713 } else {
714 return -1;
718 if (s_rc == 0) {
719 errno = ETIMEDOUT;
720 return -1;
723 return s_rc;
726 static void _modbus_tcp_free(modbus_t *ctx) {
727 free(ctx->backend_data);
728 free(ctx);
731 const modbus_backend_t _modbus_tcp_backend = {
732 _MODBUS_BACKEND_TYPE_TCP,
733 _MODBUS_TCP_HEADER_LENGTH,
734 _MODBUS_TCP_CHECKSUM_LENGTH,
735 MODBUS_TCP_MAX_ADU_LENGTH,
736 _modbus_set_slave,
737 _modbus_tcp_build_request_basis,
738 _modbus_tcp_build_response_basis,
739 _modbus_tcp_prepare_response_tid,
740 _modbus_tcp_send_msg_pre,
741 _modbus_tcp_send,
742 _modbus_tcp_receive,
743 _modbus_tcp_recv,
744 _modbus_tcp_check_integrity,
745 _modbus_tcp_pre_check_confirmation,
746 _modbus_tcp_connect,
747 _modbus_tcp_close,
748 _modbus_tcp_flush,
749 _modbus_tcp_select,
750 _modbus_tcp_free
754 const modbus_backend_t _modbus_tcp_pi_backend = {
755 _MODBUS_BACKEND_TYPE_TCP,
756 _MODBUS_TCP_HEADER_LENGTH,
757 _MODBUS_TCP_CHECKSUM_LENGTH,
758 MODBUS_TCP_MAX_ADU_LENGTH,
759 _modbus_set_slave,
760 _modbus_tcp_build_request_basis,
761 _modbus_tcp_build_response_basis,
762 _modbus_tcp_prepare_response_tid,
763 _modbus_tcp_send_msg_pre,
764 _modbus_tcp_send,
765 _modbus_tcp_receive,
766 _modbus_tcp_recv,
767 _modbus_tcp_check_integrity,
768 _modbus_tcp_pre_check_confirmation,
769 _modbus_tcp_pi_connect,
770 _modbus_tcp_close,
771 _modbus_tcp_flush,
772 _modbus_tcp_select,
773 _modbus_tcp_free
776 modbus_t* modbus_new_tcp(const char *ip, int port)
778 modbus_t *ctx;
779 modbus_tcp_t *ctx_tcp;
780 size_t dest_size;
781 size_t ret_size;
783 #if defined(OS_BSD)
784 /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
785 handler for SIGPIPE. */
786 struct sigaction sa;
788 sa.sa_handler = SIG_IGN;
789 if (sigaction(SIGPIPE, &sa, NULL) < 0) {
790 /* The debug flag can't be set here... */
791 fprintf(stderr, "Coud not install SIGPIPE handler.\n");
792 return NULL;
794 #endif
796 ctx = (modbus_t *)malloc(sizeof(modbus_t));
797 _modbus_init_common(ctx);
799 /* Could be changed after to reach a remote serial Modbus device */
800 ctx->slave = MODBUS_TCP_SLAVE;
802 ctx->backend = &_modbus_tcp_backend;
804 ctx->backend_data = (modbus_tcp_t *)malloc(sizeof(modbus_tcp_t));
805 ctx_tcp = (modbus_tcp_t *)ctx->backend_data;
807 if (ip != NULL) {
808 dest_size = sizeof(char) * 16;
809 ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
810 if (ret_size == 0) {
811 fprintf(stderr, "The IP string is empty\n");
812 modbus_free(ctx);
813 errno = EINVAL;
814 return NULL;
817 if (ret_size >= dest_size) {
818 fprintf(stderr, "The IP string has been truncated\n");
819 modbus_free(ctx);
820 errno = EINVAL;
821 return NULL;
823 } else {
824 ctx_tcp->ip[0] = '0';
826 ctx_tcp->port = port;
827 ctx_tcp->t_id = 0;
829 return ctx;
833 modbus_t* modbus_new_tcp_pi(const char *node, const char *service)
835 modbus_t *ctx;
836 modbus_tcp_pi_t *ctx_tcp_pi;
837 size_t dest_size;
838 size_t ret_size;
840 ctx = (modbus_t *)malloc(sizeof(modbus_t));
841 _modbus_init_common(ctx);
843 /* Could be changed after to reach a remote serial Modbus device */
844 ctx->slave = MODBUS_TCP_SLAVE;
846 ctx->backend = &_modbus_tcp_pi_backend;
848 ctx->backend_data = (modbus_tcp_pi_t *)malloc(sizeof(modbus_tcp_pi_t));
849 ctx_tcp_pi = (modbus_tcp_pi_t *)ctx->backend_data;
851 if (node == NULL) {
852 /* The node argument can be empty to indicate any hosts */
853 ctx_tcp_pi->node[0] = '0';
854 } else {
855 dest_size = sizeof(char) * _MODBUS_TCP_PI_NODE_LENGTH;
856 ret_size = strlcpy(ctx_tcp_pi->node, node, dest_size);
857 if (ret_size == 0) {
858 fprintf(stderr, "The node string is empty\n");
859 modbus_free(ctx);
860 errno = EINVAL;
861 return NULL;
864 if (ret_size >= dest_size) {
865 fprintf(stderr, "The node string has been truncated\n");
866 modbus_free(ctx);
867 errno = EINVAL;
868 return NULL;
872 if (service != NULL) {
873 dest_size = sizeof(char) * _MODBUS_TCP_PI_SERVICE_LENGTH;
874 ret_size = strlcpy(ctx_tcp_pi->service, service, dest_size);
875 } else {
876 /* Empty service is not allowed, error catched below. */
877 ret_size = 0;
880 if (ret_size == 0) {
881 fprintf(stderr, "The service string is empty\n");
882 modbus_free(ctx);
883 errno = EINVAL;
884 return NULL;
887 if (ret_size >= dest_size) {
888 fprintf(stderr, "The service string has been truncated\n");
889 modbus_free(ctx);
890 errno = EINVAL;
891 return NULL;
894 ctx_tcp_pi->t_id = 0;
896 return ctx;