blob: 4445a44203c9ebbcb4afab38420ee446e5913174 [file] [log] [blame]
David Pursellc25a34e2016-02-22 14:27:23 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "sysdeps.h"
18
19bool set_tcp_keepalive(int fd, int interval_sec) {
20 int enable = (interval_sec > 0);
21 if (adb_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable))) {
22 return false;
23 }
24
25 if (!enable) {
26 return true;
27 }
28
29 // Idle time before sending the first keepalive is TCP_KEEPIDLE on Linux, TCP_KEEPALIVE on Mac.
30#if defined(TCP_KEEPIDLE)
31 if (adb_setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &interval_sec, sizeof(interval_sec))) {
32 return false;
33 }
34#elif defined(TCP_KEEPALIVE)
35 if (adb_setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &interval_sec, sizeof(interval_sec))) {
36 return false;
37 }
38#endif
39
40 // TCP_KEEPINTVL and TCP_KEEPCNT are available on Linux 2.4+ and OS X 10.8+ (Mountain Lion).
41#if defined(TCP_KEEPINTVL)
42 if (adb_setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &interval_sec, sizeof(interval_sec))) {
43 return false;
44 }
45#endif
46
47#if defined(TCP_KEEPCNT)
48 // On Windows this value is hardcoded to 10. This is a reasonable value, so we do the same here
49 // to match behavior. See SO_KEEPALIVE documentation at
50 // https://msdn.microsoft.com/en-us/library/windows/desktop/ee470551(v=vs.85).aspx.
51 const int keepcnt = 10;
52 if (adb_setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt))) {
53 return false;
54 }
55#endif
56
57 return true;
58}