Add simple TCP server

This commit is contained in:
caskd 2020-02-10 12:35:53 +01:00
parent e2042e677f
commit 18dfa16d55
No known key found for this signature in database
GPG Key ID: 79DB21404E300A27
2 changed files with 51 additions and 1 deletions

View File

@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.0)
project(programmingquest LANGUAGES C)
SET(CHALLANGE format)
SET(CHALLANGE tcpserver)
add_executable(binary
src/${CHALLANGE}.c

50
src/tcpserver.c Normal file
View File

@ -0,0 +1,50 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#define die(MSG) { fprintf(stderr, "%s %s. (%i)\n", MSG, strerror(errno), errno); return errno; }
#define SVPORT 8081
#define MAXCONN 2000000
int main(int argc, char *argv[]) {
int sock_fd;
struct sockaddr_in serv_addr;
// Open socket and die if invalid file descriptor is returned
if ((sock_fd = socket(AF_INET,SOCK_STREAM, 0)) < 0)
die("Failed to open socket.");
// Set server address and port
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(SVPORT);
// Bind to socket
if (bind(sock_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
die("Couldn't bind to socket.");
// Go in passive(LISTEN) mode
if ((listen(sock_fd, MAXCONN)) < 0)
die("Failed to listen on socket.");
printf("Now listening for connections.\n");
// Accept connections
char buffer[] = "Hello, fellow navigator!\n";
for (int conncount=0;; conncount++) {
int conn_fd;
socklen_t client_len;
struct sockaddr_in client_addr;
client_len = sizeof(client_addr);
if ((conn_fd = accept(sock_fd, (struct sockaddr *) &client_addr, &client_len)) < 0)
die("Failed to accept connection.");
printf("Processed %i connections, last from %15s on port %5i.\r", conncount, inet_ntoa(client_addr.sin_addr), client_addr.sin_port);
setvbuf(stdout, NULL, _IONBF, 0);
if (send(conn_fd, buffer, strlen(buffer),0) < 0)
fprintf(stderr, "\nFailed to send data. %s.\n", strerror(errno));
if (close(conn_fd) < 0)
die("Failed to close connection.");
}
close(sock_fd);
return 1;
}