Fix address range in random-test-client
[libmodbus.git] / src / modbus-tcp.c
blobd19b36a64e0cb62b25e188b0dd8580ccd9914b3e
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 #if defined(_AIX) && !defined(MSG_DONTWAIT)
50 #define MSG_DONTWAIT MSG_NONBLOCK
51 #endif
53 #include "modbus-private.h"
55 #include "modbus-tcp.h"
56 #include "modbus-tcp-private.h"
58 #ifdef OS_WIN32
59 static int _modbus_tcp_init_win32(void)
61 /* Initialise Windows Socket API */
62 WSADATA wsaData;
64 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
65 fprintf(stderr, "WSAStartup() returned error code %d\n",
66 (unsigned int)GetLastError());
67 errno = EIO;
68 return -1;
70 return 0;
72 #endif
74 static int _modbus_set_slave(modbus_t *ctx, int slave)
76 /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */
77 if (slave >= 0 && slave <= 247) {
78 ctx->slave = slave;
79 } else if (slave == MODBUS_TCP_SLAVE) {
80 /* The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to
81 * restore the default value. */
82 ctx->slave = slave;
83 } else {
84 errno = EINVAL;
85 return -1;
88 return 0;
91 /* Builds a TCP request header */
92 static int _modbus_tcp_build_request_basis(modbus_t *ctx, int function,
93 int addr, int nb,
94 uint8_t *req)
96 modbus_tcp_t *ctx_tcp = ctx->backend_data;
98 /* Increase transaction ID */
99 if (ctx_tcp->t_id < UINT16_MAX)
100 ctx_tcp->t_id++;
101 else
102 ctx_tcp->t_id = 0;
103 req[0] = ctx_tcp->t_id >> 8;
104 req[1] = ctx_tcp->t_id & 0x00ff;
106 /* Protocol Modbus */
107 req[2] = 0;
108 req[3] = 0;
110 /* Length will be defined later by set_req_length_tcp at offsets 4
111 and 5 */
113 req[6] = ctx->slave;
114 req[7] = function;
115 req[8] = addr >> 8;
116 req[9] = addr & 0x00ff;
117 req[10] = nb >> 8;
118 req[11] = nb & 0x00ff;
120 return _MODBUS_TCP_PRESET_REQ_LENGTH;
123 /* Builds a TCP response header */
124 static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp)
126 /* Extract from MODBUS Messaging on TCP/IP Implementation
127 Guide V1.0b (page 23/46):
128 The transaction identifier is used to associate the future
129 response with the request. */
130 rsp[0] = sft->t_id >> 8;
131 rsp[1] = sft->t_id & 0x00ff;
133 /* Protocol Modbus */
134 rsp[2] = 0;
135 rsp[3] = 0;
137 /* Length will be set later by send_msg (4 and 5) */
139 /* The slave ID is copied from the indication */
140 rsp[6] = sft->slave;
141 rsp[7] = sft->function;
143 return _MODBUS_TCP_PRESET_RSP_LENGTH;
147 static int _modbus_tcp_prepare_response_tid(const uint8_t *req, int *req_length)
149 return (req[0] << 8) + req[1];
152 static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length)
154 /* Substract the header length to the message length */
155 int mbap_length = req_length - 6;
157 req[4] = mbap_length >> 8;
158 req[5] = mbap_length & 0x00FF;
160 return req_length;
163 static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length)
165 /* MSG_NOSIGNAL
166 Requests not to send SIGPIPE on errors on stream oriented
167 sockets when the other end breaks the connection. The EPIPE
168 error is still returned. */
169 return send(ctx->s, (const char *)req, req_length, MSG_NOSIGNAL);
172 static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req) {
173 return _modbus_receive_msg(ctx, req, MSG_INDICATION);
176 static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length) {
177 return recv(ctx->s, (char *)rsp, rsp_length, 0);
180 static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length)
182 return msg_length;
185 static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx, const uint8_t *req,
186 const uint8_t *rsp, int rsp_length)
188 /* Check transaction ID */
189 if (req[0] != rsp[0] || req[1] != rsp[1]) {
190 if (ctx->debug) {
191 fprintf(stderr, "Invalid transaction ID received 0x%X (not 0x%X)\n",
192 (rsp[0] << 8) + rsp[1], (req[0] << 8) + req[1]);
194 errno = EMBBADDATA;
195 return -1;
198 /* Check protocol ID */
199 if (rsp[2] != 0x0 && rsp[3] != 0x0) {
200 if (ctx->debug) {
201 fprintf(stderr, "Invalid protocol ID received 0x%X (not 0x0)\n",
202 (rsp[2] << 8) + rsp[3]);
204 errno = EMBBADDATA;
205 return -1;
208 return 0;
211 static int _modbus_tcp_set_ipv4_options(int s)
213 int rc;
214 int option;
216 /* Set the TCP no delay flag */
217 /* SOL_TCP = IPPROTO_TCP */
218 option = 1;
219 rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
220 (const void *)&option, sizeof(int));
221 if (rc == -1) {
222 return -1;
225 /* If the OS does not offer SOCK_NONBLOCK, fall back to setting FIONBIO to
226 * make sockets non-blocking */
227 /* Do not care about the return value, this is optional */
228 option = 1;
229 #if !defined(SOCK_NONBLOCK) && defined(FIONBIO)
230 #ifdef OS_WIN32
232 /* Setting FIONBIO expects an unsigned long according to MSDN */
233 u_long loption = 1;
234 ioctlsocket(s, FIONBIO, &loption);
236 #else
237 ioctl(s, FIONBIO, &option);
238 #endif
239 #endif
241 #ifndef OS_WIN32
243 * Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
244 * necessary to workaround that problem.
246 /* Set the IP low delay option */
247 option = IPTOS_LOWDELAY;
248 rc = setsockopt(s, IPPROTO_IP, IP_TOS,
249 (const void *)&option, sizeof(int));
250 if (rc == -1) {
251 return -1;
253 #endif
255 return 0;
258 static int _connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen,
259 const struct timeval *ro_tv)
261 int rc = connect(sockfd, addr, addrlen);
263 #ifdef OS_WIN32
264 int wsaError = 0;
265 if (rc == -1) {
266 wsaError = WSAGetLastError();
269 if (wsaError == WSAEWOULDBLOCK || wsaError == WSAEINPROGRESS) {
270 #else
271 if (rc == -1 && errno == EINPROGRESS) {
272 #endif
273 fd_set wset;
274 int optval;
275 socklen_t optlen = sizeof(optval);
276 struct timeval tv = *ro_tv;
278 /* Wait to be available in writing */
279 FD_ZERO(&wset);
280 FD_SET(sockfd, &wset);
281 rc = select(sockfd + 1, NULL, &wset, NULL, &tv);
282 if (rc <= 0) {
283 /* Timeout or fail */
284 return -1;
287 /* The connection is established if SO_ERROR and optval are set to 0 */
288 rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&optval, &optlen);
289 if (rc == 0 && optval == 0) {
290 return 0;
291 } else {
292 errno = ECONNREFUSED;
293 return -1;
296 return rc;
299 /* Establishes a modbus TCP connection with a Modbus server. */
300 static int _modbus_tcp_connect(modbus_t *ctx)
302 int rc;
303 /* Specialized version of sockaddr for Internet socket address (same size) */
304 struct sockaddr_in addr;
305 modbus_tcp_t *ctx_tcp = ctx->backend_data;
306 int flags = SOCK_STREAM;
308 #ifdef OS_WIN32
309 if (_modbus_tcp_init_win32() == -1) {
310 return -1;
312 #endif
314 #ifdef SOCK_CLOEXEC
315 flags |= SOCK_CLOEXEC;
316 #endif
318 #ifdef SOCK_NONBLOCK
319 flags |= SOCK_NONBLOCK;
320 #endif
322 ctx->s = socket(PF_INET, flags, 0);
323 if (ctx->s == -1) {
324 return -1;
327 rc = _modbus_tcp_set_ipv4_options(ctx->s);
328 if (rc == -1) {
329 close(ctx->s);
330 ctx->s = -1;
331 return -1;
334 if (ctx->debug) {
335 printf("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port);
338 addr.sin_family = AF_INET;
339 addr.sin_port = htons(ctx_tcp->port);
340 addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
341 rc = _connect(ctx->s, (struct sockaddr *)&addr, sizeof(addr), &ctx->response_timeout);
342 if (rc == -1) {
343 close(ctx->s);
344 ctx->s = -1;
345 return -1;
348 return 0;
351 /* Establishes a modbus TCP PI connection with a Modbus server. */
352 static int _modbus_tcp_pi_connect(modbus_t *ctx)
354 int rc;
355 struct addrinfo *ai_list;
356 struct addrinfo *ai_ptr;
357 struct addrinfo ai_hints;
358 modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
360 #ifdef OS_WIN32
361 if (_modbus_tcp_init_win32() == -1) {
362 return -1;
364 #endif
366 memset(&ai_hints, 0, sizeof(ai_hints));
367 #ifdef AI_ADDRCONFIG
368 ai_hints.ai_flags |= AI_ADDRCONFIG;
369 #endif
370 ai_hints.ai_family = AF_UNSPEC;
371 ai_hints.ai_socktype = SOCK_STREAM;
372 ai_hints.ai_addr = NULL;
373 ai_hints.ai_canonname = NULL;
374 ai_hints.ai_next = NULL;
376 ai_list = NULL;
377 rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service,
378 &ai_hints, &ai_list);
379 if (rc != 0) {
380 if (ctx->debug) {
381 fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
383 errno = ECONNREFUSED;
384 return -1;
387 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
388 int flags = ai_ptr->ai_socktype;
389 int s;
391 #ifdef SOCK_CLOEXEC
392 flags |= SOCK_CLOEXEC;
393 #endif
395 #ifdef SOCK_NONBLOCK
396 flags |= SOCK_NONBLOCK;
397 #endif
399 s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
400 if (s < 0)
401 continue;
403 if (ai_ptr->ai_family == AF_INET)
404 _modbus_tcp_set_ipv4_options(s);
406 if (ctx->debug) {
407 printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
410 rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
411 if (rc == -1) {
412 close(s);
413 continue;
416 ctx->s = s;
417 break;
420 freeaddrinfo(ai_list);
422 if (ctx->s < 0) {
423 return -1;
426 return 0;
429 /* Closes the network connection and socket in TCP mode */
430 static void _modbus_tcp_close(modbus_t *ctx)
432 if (ctx->s != -1) {
433 shutdown(ctx->s, SHUT_RDWR);
434 close(ctx->s);
435 ctx->s = -1;
439 static int _modbus_tcp_flush(modbus_t *ctx)
441 int rc;
442 int rc_sum = 0;
444 do {
445 /* Extract the garbage from the socket */
446 char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
447 #ifndef OS_WIN32
448 rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
449 #else
450 /* On Win32, it's a bit more complicated to not wait */
451 fd_set rset;
452 struct timeval tv;
454 tv.tv_sec = 0;
455 tv.tv_usec = 0;
456 FD_ZERO(&rset);
457 FD_SET(ctx->s, &rset);
458 rc = select(ctx->s+1, &rset, NULL, NULL, &tv);
459 if (rc == -1) {
460 return -1;
463 if (rc == 1) {
464 /* There is data to flush */
465 rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0);
467 #endif
468 if (rc > 0) {
469 rc_sum += rc;
471 } while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
473 return rc_sum;
476 /* Listens for any request from one or many modbus masters in TCP */
477 int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
479 int new_s;
480 int enable;
481 struct sockaddr_in addr;
482 modbus_tcp_t *ctx_tcp;
484 if (ctx == NULL) {
485 errno = EINVAL;
486 return -1;
489 ctx_tcp = ctx->backend_data;
491 #ifdef OS_WIN32
492 if (_modbus_tcp_init_win32() == -1) {
493 return -1;
495 #endif
497 new_s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
498 if (new_s == -1) {
499 return -1;
502 enable = 1;
503 if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR,
504 (char *)&enable, sizeof(enable)) == -1) {
505 close(new_s);
506 return -1;
509 memset(&addr, 0, sizeof(addr));
510 addr.sin_family = AF_INET;
511 /* If the modbus port is < to 1024, we need the setuid root. */
512 addr.sin_port = htons(ctx_tcp->port);
513 if (ctx_tcp->ip[0] == '0') {
514 /* Listen any addresses */
515 addr.sin_addr.s_addr = htonl(INADDR_ANY);
516 } else {
517 /* Listen only specified IP address */
518 addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
520 if (bind(new_s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
521 close(new_s);
522 return -1;
525 if (listen(new_s, nb_connection) == -1) {
526 close(new_s);
527 return -1;
530 return new_s;
533 int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
535 int rc;
536 struct addrinfo *ai_list;
537 struct addrinfo *ai_ptr;
538 struct addrinfo ai_hints;
539 const char *node;
540 const char *service;
541 int new_s;
542 modbus_tcp_pi_t *ctx_tcp_pi;
544 if (ctx == NULL) {
545 errno = EINVAL;
546 return -1;
549 ctx_tcp_pi = ctx->backend_data;
551 #ifdef OS_WIN32
552 if (_modbus_tcp_init_win32() == -1) {
553 return -1;
555 #endif
557 if (ctx_tcp_pi->node[0] == 0) {
558 node = NULL; /* == any */
559 } else {
560 node = ctx_tcp_pi->node;
563 if (ctx_tcp_pi->service[0] == 0) {
564 service = "502";
565 } else {
566 service = ctx_tcp_pi->service;
569 memset(&ai_hints, 0, sizeof (ai_hints));
570 /* If node is not NULL, than the AI_PASSIVE flag is ignored. */
571 ai_hints.ai_flags |= AI_PASSIVE;
572 #ifdef AI_ADDRCONFIG
573 ai_hints.ai_flags |= AI_ADDRCONFIG;
574 #endif
575 ai_hints.ai_family = AF_UNSPEC;
576 ai_hints.ai_socktype = SOCK_STREAM;
577 ai_hints.ai_addr = NULL;
578 ai_hints.ai_canonname = NULL;
579 ai_hints.ai_next = NULL;
581 ai_list = NULL;
582 rc = getaddrinfo(node, service, &ai_hints, &ai_list);
583 if (rc != 0) {
584 if (ctx->debug) {
585 fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
587 errno = ECONNREFUSED;
588 return -1;
591 new_s = -1;
592 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
593 int s;
595 s = socket(ai_ptr->ai_family, ai_ptr->ai_socktype,
596 ai_ptr->ai_protocol);
597 if (s < 0) {
598 if (ctx->debug) {
599 perror("socket");
601 continue;
602 } else {
603 int enable = 1;
604 rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
605 (void *)&enable, sizeof (enable));
606 if (rc != 0) {
607 close(s);
608 if (ctx->debug) {
609 perror("setsockopt");
611 continue;
615 rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
616 if (rc != 0) {
617 close(s);
618 if (ctx->debug) {
619 perror("bind");
621 continue;
624 rc = listen(s, nb_connection);
625 if (rc != 0) {
626 close(s);
627 if (ctx->debug) {
628 perror("listen");
630 continue;
633 new_s = s;
634 break;
636 freeaddrinfo(ai_list);
638 if (new_s < 0) {
639 return -1;
642 return new_s;
645 int modbus_tcp_accept(modbus_t *ctx, int *s)
647 struct sockaddr_in addr;
648 socklen_t addrlen;
650 if (ctx == NULL) {
651 errno = EINVAL;
652 return -1;
655 addrlen = sizeof(addr);
656 #ifdef HAVE_ACCEPT4
657 /* Inherit socket flags and use accept4 call */
658 ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
659 #else
660 ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
661 #endif
663 if (ctx->s == -1) {
664 close(*s);
665 *s = -1;
666 return -1;
669 if (ctx->debug) {
670 printf("The client connection from %s is accepted\n",
671 inet_ntoa(addr.sin_addr));
674 return ctx->s;
677 int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
679 struct sockaddr_storage addr;
680 socklen_t addrlen;
682 if (ctx == NULL) {
683 errno = EINVAL;
684 return -1;
687 addrlen = sizeof(addr);
688 #ifdef HAVE_ACCEPT4
689 /* Inherit socket flags and use accept4 call */
690 ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
691 #else
692 ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
693 #endif
694 if (ctx->s == -1) {
695 close(*s);
696 *s = -1;
699 if (ctx->debug) {
700 printf("The client connection is accepted.\n");
703 return ctx->s;
706 static int _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
708 int s_rc;
709 while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) {
710 if (errno == EINTR) {
711 if (ctx->debug) {
712 fprintf(stderr, "A non blocked signal was caught\n");
714 /* Necessary after an error */
715 FD_ZERO(rset);
716 FD_SET(ctx->s, rset);
717 } else {
718 return -1;
722 if (s_rc == 0) {
723 errno = ETIMEDOUT;
724 return -1;
727 return s_rc;
730 static void _modbus_tcp_free(modbus_t *ctx) {
731 free(ctx->backend_data);
732 free(ctx);
735 const modbus_backend_t _modbus_tcp_backend = {
736 _MODBUS_BACKEND_TYPE_TCP,
737 _MODBUS_TCP_HEADER_LENGTH,
738 _MODBUS_TCP_CHECKSUM_LENGTH,
739 MODBUS_TCP_MAX_ADU_LENGTH,
740 _modbus_set_slave,
741 _modbus_tcp_build_request_basis,
742 _modbus_tcp_build_response_basis,
743 _modbus_tcp_prepare_response_tid,
744 _modbus_tcp_send_msg_pre,
745 _modbus_tcp_send,
746 _modbus_tcp_receive,
747 _modbus_tcp_recv,
748 _modbus_tcp_check_integrity,
749 _modbus_tcp_pre_check_confirmation,
750 _modbus_tcp_connect,
751 _modbus_tcp_close,
752 _modbus_tcp_flush,
753 _modbus_tcp_select,
754 _modbus_tcp_free
758 const modbus_backend_t _modbus_tcp_pi_backend = {
759 _MODBUS_BACKEND_TYPE_TCP,
760 _MODBUS_TCP_HEADER_LENGTH,
761 _MODBUS_TCP_CHECKSUM_LENGTH,
762 MODBUS_TCP_MAX_ADU_LENGTH,
763 _modbus_set_slave,
764 _modbus_tcp_build_request_basis,
765 _modbus_tcp_build_response_basis,
766 _modbus_tcp_prepare_response_tid,
767 _modbus_tcp_send_msg_pre,
768 _modbus_tcp_send,
769 _modbus_tcp_receive,
770 _modbus_tcp_recv,
771 _modbus_tcp_check_integrity,
772 _modbus_tcp_pre_check_confirmation,
773 _modbus_tcp_pi_connect,
774 _modbus_tcp_close,
775 _modbus_tcp_flush,
776 _modbus_tcp_select,
777 _modbus_tcp_free
780 modbus_t* modbus_new_tcp(const char *ip, int port)
782 modbus_t *ctx;
783 modbus_tcp_t *ctx_tcp;
784 size_t dest_size;
785 size_t ret_size;
787 #if defined(OS_BSD)
788 /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
789 handler for SIGPIPE. */
790 struct sigaction sa;
792 sa.sa_handler = SIG_IGN;
793 if (sigaction(SIGPIPE, &sa, NULL) < 0) {
794 /* The debug flag can't be set here... */
795 fprintf(stderr, "Coud not install SIGPIPE handler.\n");
796 return NULL;
798 #endif
800 ctx = (modbus_t *)malloc(sizeof(modbus_t));
801 _modbus_init_common(ctx);
803 /* Could be changed after to reach a remote serial Modbus device */
804 ctx->slave = MODBUS_TCP_SLAVE;
806 ctx->backend = &_modbus_tcp_backend;
808 ctx->backend_data = (modbus_tcp_t *)malloc(sizeof(modbus_tcp_t));
809 ctx_tcp = (modbus_tcp_t *)ctx->backend_data;
811 if (ip != NULL) {
812 dest_size = sizeof(char) * 16;
813 ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
814 if (ret_size == 0) {
815 fprintf(stderr, "The IP string is empty\n");
816 modbus_free(ctx);
817 errno = EINVAL;
818 return NULL;
821 if (ret_size >= dest_size) {
822 fprintf(stderr, "The IP string has been truncated\n");
823 modbus_free(ctx);
824 errno = EINVAL;
825 return NULL;
827 } else {
828 ctx_tcp->ip[0] = '0';
830 ctx_tcp->port = port;
831 ctx_tcp->t_id = 0;
833 return ctx;
837 modbus_t* modbus_new_tcp_pi(const char *node, const char *service)
839 modbus_t *ctx;
840 modbus_tcp_pi_t *ctx_tcp_pi;
841 size_t dest_size;
842 size_t ret_size;
844 ctx = (modbus_t *)malloc(sizeof(modbus_t));
845 _modbus_init_common(ctx);
847 /* Could be changed after to reach a remote serial Modbus device */
848 ctx->slave = MODBUS_TCP_SLAVE;
850 ctx->backend = &_modbus_tcp_pi_backend;
852 ctx->backend_data = (modbus_tcp_pi_t *)malloc(sizeof(modbus_tcp_pi_t));
853 ctx_tcp_pi = (modbus_tcp_pi_t *)ctx->backend_data;
855 if (node == NULL) {
856 /* The node argument can be empty to indicate any hosts */
857 ctx_tcp_pi->node[0] = '0';
858 } else {
859 dest_size = sizeof(char) * _MODBUS_TCP_PI_NODE_LENGTH;
860 ret_size = strlcpy(ctx_tcp_pi->node, node, dest_size);
861 if (ret_size == 0) {
862 fprintf(stderr, "The node string is empty\n");
863 modbus_free(ctx);
864 errno = EINVAL;
865 return NULL;
868 if (ret_size >= dest_size) {
869 fprintf(stderr, "The node string has been truncated\n");
870 modbus_free(ctx);
871 errno = EINVAL;
872 return NULL;
876 if (service != NULL) {
877 dest_size = sizeof(char) * _MODBUS_TCP_PI_SERVICE_LENGTH;
878 ret_size = strlcpy(ctx_tcp_pi->service, service, dest_size);
879 } else {
880 /* Empty service is not allowed, error catched below. */
881 ret_size = 0;
884 if (ret_size == 0) {
885 fprintf(stderr, "The service string is empty\n");
886 modbus_free(ctx);
887 errno = EINVAL;
888 return NULL;
891 if (ret_size >= dest_size) {
892 fprintf(stderr, "The service string has been truncated\n");
893 modbus_free(ctx);
894 errno = EINVAL;
895 return NULL;
898 ctx_tcp_pi->t_id = 0;
900 return ctx;