From 5c480b5db3d14f37682eee1a6ae431b88ead0f9e Mon Sep 17 00:00:00 2001 From: Xiaofeng Liu Date: Tue, 5 Dec 2017 10:25:16 +0100 Subject: lib: add a function to configure tcp keepalive parameters New function setsockopt_tcp_keepalive() is added to enable TCP keepalive mechanism for specified socket. Also TCP keepalive idle time, interval and maximum probes are configured. Signed-off-by: Xiaofeng Liu Signed-off-by: Philippe Guibert --- lib/sockopt.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'lib/sockopt.c') diff --git a/lib/sockopt.c b/lib/sockopt.c index 45f3c2333..a66a5224e 100644 --- a/lib/sockopt.c +++ b/lib/sockopt.c @@ -699,3 +699,52 @@ int sockopt_tcp_mss_get(int sock) return tcp_maxseg; } + +int setsockopt_tcp_keepalive(int sock, uint16_t keepalive_idle, + uint16_t keepalive_intvl, + uint16_t keepalive_probes) +{ + int val = 1; + + if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) < 0) { + flog_err_sys(EC_LIB_SYSTEM_CALL, + "%s failed: setsockopt SO_KEEPALIVE (%d): %s", + __func__, sock, safe_strerror(errno)); + return -1; + } + +#if defined __OpenBSD__ + return 0; +#else + /* Send first probe after keepalive_idle seconds */ + val = keepalive_idle; + if (setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < + 0) { + flog_err_sys(EC_LIB_SYSTEM_CALL, + "%s failed: setsockopt TCP_KEEPIDLE (%d): %s", + __func__, sock, safe_strerror(errno)); + return -1; + } + + /* Set interval between two probes */ + val = keepalive_intvl; + if (setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < + 0) { + flog_err_sys(EC_LIB_SYSTEM_CALL, + "%s failed: setsockopt TCP_KEEPINTVL (%d): %s", + __func__, sock, safe_strerror(errno)); + return -1; + } + + /* Set maximum probes */ + val = keepalive_probes; + if (setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) { + flog_err_sys(EC_LIB_SYSTEM_CALL, + "%s failed: setsockopt TCP_KEEPCNT (%d): %s", + __func__, sock, safe_strerror(errno)); + return -1; + } + + return 0; +#endif +} -- cgit v1.2.3