Last active
January 19, 2023 10:59
-
-
Save lemonmojo/1b7f957aed60a65c121e8067d5d93483 to your computer and use it in GitHub Desktop.
A small utility to test TCP keep-alive on macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// keepalivetest.c | |
// | |
// Created by Felix Deimel on 07.11.19 | |
// Copyright (c) 2019 Felix Deimel | |
// | |
// [INSTRUCTIONS] | |
// | |
// Compile with "cc -o keepalivetest keepalivetest.c" | |
// Run with "./keepalivetest HOSTNAME PORT" | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
#include <netinet/tcp.h> | |
int main(int argc, const char * argv[]) { | |
if (argc < 3) { | |
printf("Usage: keepalivetest HOSTNAME PORT\n"); | |
return 1; | |
} | |
const char* hostname = argv[1]; | |
const int port = atoi(argv[2]); | |
// socket create and varification | |
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
if (sockfd == -1) { | |
printf("Error: Socket creation failed.\n"); | |
return 1; | |
} | |
// enable TCP keep-alive | |
int enablekeepalive = 1; | |
if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &enablekeepalive, sizeof(int)) < 0) { | |
printf("Error: Setting SO_KEEPALIVE failed.\n"); | |
return 1; | |
} | |
int idle = 1; | |
if (setsockopt(sockfd, IPPROTO_TCP, /* TCP_KEEPIDLE */ TCP_KEEPALIVE, &idle, sizeof(int)) < 0) { | |
printf("Error: Setting TCP_KEEPALIVE failed.\n"); | |
return 1; | |
} | |
int interval = 1; | |
if (setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(int)) < 0) { | |
printf("Error: Setting TCP_KEEPINTVL failed.\n"); | |
return 1; | |
} | |
int maxpkt = 10; | |
if (setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, &maxpkt, sizeof(int)) < 0) { | |
printf("Error: Setting TCP_KEEPCNT failed.\n"); | |
return 1; | |
} | |
// assign IP and Port | |
struct sockaddr_in servaddr; | |
bzero(&servaddr, sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = inet_addr(hostname); | |
servaddr.sin_port = htons(port); | |
// connect the client socket to server socket | |
if (connect(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) { | |
printf("Error: Connection with the server failed.\n"); | |
return 1; | |
} else { | |
printf("Connected to the server.\nPress enter to close the connection... "); | |
} | |
for (;;) { | |
while (getchar() != '\n') | |
; | |
break; | |
} | |
// close the socket | |
close(sockfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment