0

I am using this code to setup a socket to detect a network error:

int socket_keepalive(int s, int ktime, int kinterval, int kprobes) {
    int enable = 1;
    if(setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(int)) < 0) {
            printf("setsockopt SO_KEEPALIVE failed (%s)\n", strerror(errno));
            return -1;
    }

    if(setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, &ktime, sizeof(int) < 0)) {
            printf("setsockopt TCP_KEEPIDLE failed\n");
            perror("SO_KEEPALIVE: ");
            return -1;
    }

    if(setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, &kinterval, sizeof(int) < 0)) {
            printf("setsockopt TCP_KEEPINTVL failed\n");
            perror("TCP_KEEPINTVL: ");
            return -1;
    }

    if(setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, &kprobes, sizeof(int) < 0)) {
            printf("setsockopt TCP_KEEPCNT failed\n");
            perror("TCP_KEEPCNT: ");
            return -1;
    }

    return 0;
}

I am calling the above function like this:

socket_keepalive(sock, 30, 10, 1);

I expect the socket to be disconnected after 40 seconds after a network error. However, it takes almost 170 seconds after a network error on the remote side.

Any idea what I am doing wrong?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rahul
  • 390
  • 4
  • 14
  • 1
    The connection has to be idle for 30 seconds before it starts sending keepalives. If the application tries to send anything when the network error happens, the normal TCP retry mechanism is used, not the keepalive mechanism. – Barmar Sep 13 '19 at 05:55
  • See https://stackoverflow.com/questions/33553410/tcp-retranmission-timer-overrides-kills-tcp-keepalive-timer-delaying-disconnect – Barmar Sep 13 '19 at 05:55
  • Good info. How do I override retries2? – Rahul Sep 13 '19 at 06:21
  • I don't think you can override it at runtime, it's a kernel setting. – Barmar Sep 13 '19 at 06:22

0 Answers0