Skip to content

Commit 2d90320

Browse files
NikolasK-gitNikolasK-source
authored andcommitted
socket options
1 parent 8af36b8 commit 2d90320

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/Modbus_TCP_Slave.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55

66
#include "Modbus_TCP_Slave.hpp"
77

8+
#include <netinet/in.h>
9+
#include <netinet/tcp.h>
810
#include <stdexcept>
11+
#include <sys/socket.h>
12+
#include <system_error>
913
#include <unistd.h>
1014

1115
namespace Modbus {
@@ -42,6 +46,19 @@ Slave::Slave(const std::string &ip, unsigned short port, modbus_mapping_t *mappi
4246
const std::string error_msg = modbus_strerror(errno);
4347
throw std::runtime_error("failed to create tcp socket: " + error_msg);
4448
}
49+
50+
// set socket options
51+
int keepalive = 1;
52+
int tmp = setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
53+
if (tmp != 0) {
54+
throw std::system_error(errno, std::generic_category(), "Failed to set socket option SO_KEEPALIVE");
55+
}
56+
57+
unsigned user_timeout = 5000;
58+
tmp = setsockopt(socket, IPPROTO_TCP, TCP_USER_TIMEOUT, &keepalive, sizeof(user_timeout));
59+
if (tmp != 0) {
60+
throw std::system_error(errno, std::generic_category(), "Failed to set socket option SO_KEEPALIVE");
61+
}
4562
}
4663

4764
Slave::~Slave() {

0 commit comments

Comments
 (0)