Created
March 26, 2020 00:47
-
-
Save YoukouTenhouin/e2bf8fcc474b82ca936f6ecf0f8510b8 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 <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/ip.h> | |
#include <arpa/inet.h> | |
int | |
bind_sock() | |
{ | |
int fd = socket(AF_INET, SOCK_STREAM, 0); | |
if (fd < 0) { | |
perror("socket"); | |
exit(1); | |
} | |
int val = 1; | |
/* SO_REUSEPORT implies SO_REUSEADDR */ | |
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val)) < 0) { | |
perror("setsockopt"); | |
exit(1); | |
} | |
struct sockaddr_in addr; | |
addr.sin_family = AF_INET; | |
addr.sin_addr.s_addr = INADDR_ANY; | |
addr.sin_port = htons(12345); | |
memset(&addr.sin_zero, 0, sizeof(addr.sin_zero)); | |
if (bind(fd, (void*)&addr, sizeof(addr)) < 0) { | |
perror("bind"); | |
exit(1); | |
} | |
if (listen(fd, 128) < 0) { | |
perror("listen"); | |
exit(1); | |
} | |
return fd; | |
} | |
int | |
main() { | |
int fd = bind_sock(); | |
printf("telnet to 127.0.0.1:12345 and press enter:"); | |
getchar(); | |
int fd2 = bind_sock(); | |
printf("open new connections if needed, and press enter again:"); | |
getchar(); | |
close(fd); | |
char buf[] = "ACCEPTED\r\n"; | |
while (1) { | |
int cfd = accept(fd2, NULL, NULL); | |
send(cfd, buf, strlen(buf), MSG_NOSIGNAL); | |
close(cfd); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment