Created
June 24, 2020 17:35
-
-
Save Izzette/0942afa6ac9adabf202e147857150993 to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <assert.h> | |
#include <netdb.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netinet/ip.h> | |
#include <arpa/inet.h> | |
int main(int argc, const char *argv[]) { | |
if (argc != 2) { | |
const char *progname = (argc) ? argv[0] : "backlog-test"; | |
fprintf(stderr, "Usage: %s <backlog>\n", progname); | |
return 1; | |
} | |
int backlog = atoi(argv[1]); | |
fprintf(stderr, "Using backlog of %d\n", backlog); | |
struct protoent *tcp_protent = getprotobyname("tcp"); | |
assert(tcp_protent); | |
int sockfd = socket(AF_INET, SOCK_STREAM, tcp_protent->p_proto); | |
if (sockfd == -1) { | |
fprintf(stderr, "Failed to create socket: %s\n", strerror(errno)); | |
return 1; | |
} | |
fprintf(stderr, "Created socket %d\n", sockfd); | |
if (listen(sockfd, backlog)) { | |
fprintf(stderr, "Failed to listen on socket: %s\n", strerror(errno)); | |
return 1; | |
} | |
struct sockaddr_in sockaddr; | |
socklen_t socklen = sizeof(sockaddr); | |
assert(!getsockname(sockfd, (struct sockaddr *)&sockaddr, &socklen)); | |
fprintf(stderr, "Listening on all interfaces port %d\n", ntohs(sockaddr.sin_port)); | |
struct sockaddr_in sockaddr_remote; | |
socklen_t socklen_remote = sizeof(sockaddr_remote); | |
int connfd; | |
while ((connfd = accept(sockfd, (struct sockaddr *)&sockaddr_remote, &socklen_remote)) != -1) { | |
fprintf(stderr, "Accepted connection from %s:%d\n", inet_ntoa(sockaddr_remote.sin_addr), ntohs(sockaddr_remote.sin_port)); | |
fputs("Closing connection\n", stderr); | |
assert(!close(connfd)); | |
} | |
fprintf(stderr, "Failed to accept connection on socket: %s\n", strerror(errno)); | |
assert(!close(sockfd)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment