Last active
December 11, 2020 23:45
-
-
Save Keno/275a2346100e4f5a7d70de6401748a02 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <poll.h> | |
#include <signal.h> | |
#define CLIENT_PORT 9999 | |
#define SERVER_PORT 10000 | |
#define CHECK(cond) { \ | |
if (!(cond)) { \ | |
printf("Failed at tcpstat.c:%d (%d): %s\n", __LINE__, errno, #cond); \ | |
exit(1); \ | |
} \ | |
} | |
int main() { | |
printf("PID id %d\n", getpid()); | |
int sock = socket(AF_INET, SOCK_STREAM, 0); | |
CHECK(sock >= 0); | |
int yes = 1; | |
struct sockaddr_in addr; | |
addr.sin_family = AF_INET; | |
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); | |
addr.sin_port = htons(CLIENT_PORT); | |
CHECK(0 == bind(sock, &addr, sizeof(addr))); | |
// Create a connection and leave it in TIME_WAIT state | |
if (fork() == 0) { | |
close(sock); | |
int server = socket(AF_INET, SOCK_STREAM, 0); | |
CHECK(server >= 0); | |
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); | |
addr.sin_port = htons(SERVER_PORT); | |
CHECK(0 == bind(server, &addr, sizeof(addr))); | |
CHECK(0 == listen(server, 3)); | |
int client = accept(server, NULL, 0); | |
close(client); | |
return 0; | |
} | |
sleep(1); | |
addr.sin_port = htons(SERVER_PORT); | |
CHECK(0 == connect(sock, &addr, sizeof(addr))); | |
// Make sure the client connection ends up in CLOSE_WAIT | |
sleep(3); | |
close(sock); | |
// Wait for transition to CLOSED | |
sleep(1); | |
sock = socket(AF_INET, SOCK_STREAM, 0); | |
CHECK(sock >= 0); | |
addr.sin_port = htons(CLIENT_PORT); | |
CHECK(0 == bind(sock, &addr, sizeof(addr))); | |
pid_t pid; | |
if ((pid = fork()) == 0) { | |
close(sock); | |
int server = socket(AF_INET, SOCK_STREAM, 0); | |
CHECK(server >= 0); | |
CHECK(0 == setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes))); | |
addr.sin_port = htons(SERVER_PORT); | |
printf("Binding...\n"); | |
CHECK(0 == bind(server, &addr, sizeof(addr))); | |
CHECK(0 == listen(sock, 3)); | |
printf("Waiting...\n"); | |
int client = accept(server, NULL, 0); | |
close(client); | |
return 0; | |
} | |
sleep(5); | |
addr.sin_port = htons(SERVER_PORT); | |
printf("Attempting to connect\n"); | |
int err = connect(sock, &addr, sizeof(addr)); | |
if (err == 0) { | |
printf("Ok\n"); | |
} else { | |
printf("Failed %d\n", errno); | |
kill(pid, SIGKILL); | |
} | |
// Make sure the client connection ends up in CLOSE_WAIT | |
sleep(3); | |
close(sock); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment