From c27f2cba1e3b7e1289f71dcb4c7863e23a7182a7 Mon Sep 17 00:00:00 2001 From: Benoit Maurin Date: Fri, 4 Oct 2024 20:36:11 +0200 Subject: [PATCH] TCP sendto removal + error when UDP for hostnames - UDP inet_pton(remote_ip)'s result is not checked -> the server ends up sending packets to the null address when a hostname is given instead of a IPv4 address. A error is now raised - TCP is using sendto() instead of send(). We can thus remove a useless inet_pton() call (which moreover differs from the gethostbyaddr used in setup_port() - possible issues when using hostnames) Signed-off-by: Benoit Maurin --- src/mavsdk/core/tcp_client_connection.cpp | 11 +++-------- src/mavsdk/core/udp_connection.cpp | 11 +++++++++-- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/mavsdk/core/tcp_client_connection.cpp b/src/mavsdk/core/tcp_client_connection.cpp index a4740d925..1b2c958a1 100644 --- a/src/mavsdk/core/tcp_client_connection.cpp +++ b/src/mavsdk/core/tcp_client_connection.cpp @@ -163,16 +163,11 @@ bool TcpClientConnection::send_message(const mavlink_message_t& message) auto flags = MSG_NOSIGNAL; #endif - const auto send_len = sendto( - _socket_fd.get(), - reinterpret_cast(buffer), - buffer_len, - flags, - reinterpret_cast(&dest_addr), - sizeof(dest_addr)); + const auto send_len = + send(_socket_fd.get(), reinterpret_cast(buffer), buffer_len, flags); if (send_len != buffer_len) { - LogErr() << "sendto failure: " << GET_ERROR(errno); + LogErr() << "send failure: " << GET_ERROR(errno); _is_ok = false; return false; } diff --git a/src/mavsdk/core/udp_connection.cpp b/src/mavsdk/core/udp_connection.cpp index ab5998d4b..f9fd68ff2 100644 --- a/src/mavsdk/core/udp_connection.cpp +++ b/src/mavsdk/core/udp_connection.cpp @@ -77,7 +77,10 @@ ConnectionResult UdpConnection::setup_port() struct sockaddr_in addr {}; addr.sin_family = AF_INET; - inet_pton(AF_INET, _local_ip.c_str(), &(addr.sin_addr)); + if (inet_pton(AF_INET, _local_ip.c_str(), &(addr.sin_addr)) != 1) { + LogErr() << "inet_pton failure for address: " << _local_ip; + return ConnectionResult::SocketError; + } addr.sin_port = htons(_local_port_number); if (bind(_socket_fd.get(), reinterpret_cast(&addr), sizeof(addr)) != 0) { @@ -129,7 +132,11 @@ bool UdpConnection::send_message(const mavlink_message_t& message) struct sockaddr_in dest_addr {}; dest_addr.sin_family = AF_INET; - inet_pton(AF_INET, remote.ip.c_str(), &dest_addr.sin_addr.s_addr); + if (inet_pton(AF_INET, remote.ip.c_str(), &dest_addr.sin_addr.s_addr) != 1) { + LogErr() << "inet_pton failure for address: " << remote.ip; + send_successful = false; + continue; + } dest_addr.sin_port = htons(remote.port_number); uint8_t buffer[MAVLINK_MAX_PACKET_LEN];