From 4fa86214f1915e83c6ad5cb1c8d6c42e66696b46 Mon Sep 17 00:00:00 2001 From: Stuart Miller Date: Fri, 7 Jun 2024 16:50:20 -0500 Subject: [PATCH] Add a timeout argument to TCPClient. --- include/mav/TCPClient.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/include/mav/TCPClient.h b/include/mav/TCPClient.h index 5eacce2..69913e3 100644 --- a/include/mav/TCPClient.h +++ b/include/mav/TCPClient.h @@ -55,12 +55,19 @@ namespace mav { public: - TCPClient(const std::string& address, int port) { + TCPClient(const std::string& address, int port, int timeout = -1) { _socket = socket(AF_INET, SOCK_STREAM, 0); if (_socket < 0) { throw NetworkError("Could not create socket", errno); } + if (timeout > 0) { + struct timeval send_timeout; + send_timeout.tv_sec = 0; + send_timeout.tv_usec = timeout * 1000; // timeout is in ms + setsockopt(_socket, SOL_SOCKET, SO_SNDTIMEO, &send_timeout, sizeof(send_timeout)); + } + struct hostent *hp; hp = gethostbyname(address.c_str()); if (hp == nullptr) {