this repo has no description
1// Project Includes
2#include "server.hpp"
3// Standard Library Includes
4#include <filesystem>
5#include <netinet/in.h>
6#include <print>
7#include <stdexcept>
8
9Server::Server(uint16_t port, std::string_view root_directory) : m_context(ServerContext()), m_server_fd(-1)
10{
11 m_context.m_root_directory = std::filesystem::canonical(root_directory);
12 std::println("Starting server http://localhost:{} with root directory '{}'", port,
13 m_context.m_root_directory.string());
14 // AF_INET: IPv4, SOCK_STREAM: TCP, 0: default protocol
15 int fd = socket(AF_INET, SOCK_STREAM, 0);
16 if (fd < 0)
17 {
18 throw std::runtime_error("Failed to create socket");
19 }
20 m_server_fd = FileDescriptor(fd);
21 sockaddr_in addr = {};
22 addr.sin_family = AF_INET; // IPv4
23 addr.sin_addr.s_addr = INADDR_ANY; // Bind to all interfaces
24 addr.sin_port = htons(port); // Convert port to network byte order
25 // SO_REUSEADDR option to reuse the address
26 int opt = 1;
27 if (setsockopt(m_server_fd.get(), SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
28 {
29 throw std::runtime_error("Failed to set socket options");
30 }
31
32 // Bind the socket to the specified port
33 if (bind(m_server_fd.get(), (sockaddr *)&addr, sizeof(addr)) < 0)
34 {
35 throw std::runtime_error("Failed to bind socket");
36 }
37
38 if (listen(m_server_fd.get(), SOMAXCONN) < 0)
39 {
40 throw std::runtime_error("Failed to listen on socket");
41 }
42}