Created
March 26, 2020 09:54
-
-
Save YoukouTenhouin/068dd21075d14c17f3709ce391ee22cf 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() { | |
char buf[] = "ACCEPTED\r\n"; | |
int fd = bind_sock(); | |
if (fork()) { | |
close(fd); | |
fd = bind_sock(); | |
while (1) { | |
int cfd = accept(fd, NULL, NULL); | |
send(cfd, buf, strlen(buf), MSG_NOSIGNAL); | |
close(cfd); | |
} | |
} else { | |
printf("telnet to 127.0.0.1:12345 and press enter:"); | |
getchar(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment