From 5a6efecf78112f2e882473e6610c9b1f2e1cdada Mon Sep 17 00:00:00 2001 From: Stéphane Raimbault Date: Sun, 27 Nov 2022 23:19:29 +0100 Subject: [PATCH] Replace inet_addr by inet_pton calls --- src/modbus-tcp.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/modbus-tcp.c b/src/modbus-tcp.c index 081ceee..410737b 100644 --- a/src/modbus-tcp.c +++ b/src/modbus-tcp.c @@ -351,7 +351,16 @@ static int _modbus_tcp_connect(modbus_t *ctx) addr.sin_family = AF_INET; addr.sin_port = htons(ctx_tcp->port); - addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip); + rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr)); + if (rc <= 0) { + if (ctx->debug) { + fprintf(stderr, "Invalid IP address: %s\n", ctx_tcp->ip); + } + close(ctx->s); + ctx->s = -1; + return -1; + } + rc = _connect(ctx->s, (struct sockaddr *) &addr, sizeof(addr), &ctx->response_timeout); if (rc == -1) { @@ -495,6 +504,7 @@ int modbus_tcp_listen(modbus_t *ctx, int nb_connection) int flags; struct sockaddr_in addr; modbus_tcp_t *ctx_tcp; + int rc; if (ctx == NULL) { errno = EINVAL; @@ -536,8 +546,17 @@ int modbus_tcp_listen(modbus_t *ctx, int nb_connection) addr.sin_addr.s_addr = htonl(INADDR_ANY); } else { /* Listen only specified IP address */ - addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip); + rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr)); + if (rc <= 0) { + if (ctx->debug) { + fprintf(stderr, "Invalid IP address: %s\n", ctx_tcp->ip); + } + close(ctx->s); + ctx->s = -1; + return -1; + } } + if (bind(new_s, (struct sockaddr *) &addr, sizeof(addr)) == -1) { close(new_s); return -1; -- libgit2 0.21.4