SocketOption.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (C) 2018 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. #include "netdutils/SocketOption.h"
  17. #include <netinet/in.h>
  18. #include <netinet/tcp.h>
  19. #include <sys/socket.h>
  20. #include <utility>
  21. #include "netdutils/Syscalls.h"
  22. namespace android {
  23. namespace netdutils {
  24. Status enableSockopt(Fd sock, int level, int optname) {
  25. auto& sys = sSyscalls.get();
  26. const int on = 1;
  27. return sys.setsockopt(sock, level, optname, &on, sizeof(on));
  28. }
  29. Status enableTcpKeepAlives(Fd sock, unsigned idleTime, unsigned numProbes, unsigned probeInterval) {
  30. RETURN_IF_NOT_OK(enableSockopt(sock, SOL_SOCKET, SO_KEEPALIVE));
  31. auto& sys = sSyscalls.get();
  32. if (idleTime != 0) {
  33. RETURN_IF_NOT_OK(sys.setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &idleTime, sizeof(idleTime)));
  34. }
  35. if (numProbes != 0) {
  36. RETURN_IF_NOT_OK(sys.setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &numProbes, sizeof(numProbes)));
  37. }
  38. if (probeInterval != 0) {
  39. RETURN_IF_NOT_OK(sys.setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &probeInterval,
  40. sizeof(probeInterval)));
  41. }
  42. return status::ok;
  43. }
  44. } // namespace netdutils
  45. } // namespace android