summaryrefslogtreecommitdiff
path: root/src/ServerConnection.cpp
blob: afe9bcb35b292d50c46224ea68d6f48745b75e67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "ServerConnection.h"

#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include "ClientConnection.h"

static void error_and_die(const char* message)
{
	perror(message);
	exit(1);
}

ServerConnection::ServerConnection(int port)
{
	sockaddr_in address;
	int socket_options = 1;

	if ((m_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		error_and_die("Failed to create socket");

	if (setsockopt(m_socket_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &socket_options, sizeof(socket_options)))
		error_and_die("setsockopt");

	address.sin_family = AF_INET;
	address.sin_addr.s_addr = htonl(INADDR_ANY);
	address.sin_port = htons(port);

	if ((bind(m_socket_fd, (sockaddr*)&address, sizeof(address))) < 0)
		error_and_die("bind");

	if ((listen(m_socket_fd, 10)) < 0)
		error_and_die("listen");
}

ClientConnection ServerConnection::accept_client_connection()
{
	int client_socket = accept(m_socket_fd, (sockaddr*)nullptr, nullptr);
	return ClientConnection(client_socket);
}