// Project Includes #include "server.hpp" // Standard Library Includes #include #include #include #include Server::Server(uint16_t port, std::string_view root_directory) : m_context(ServerContext()), m_server_fd(-1) { m_context.m_root_directory = std::filesystem::canonical(root_directory); std::println("Starting server http://localhost:{} with root directory '{}'", port, m_context.m_root_directory.string()); // AF_INET: IPv4, SOCK_STREAM: TCP, 0: default protocol int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { throw std::runtime_error("Failed to create socket"); } m_server_fd = FileDescriptor(fd); sockaddr_in addr = {}; addr.sin_family = AF_INET; // IPv4 addr.sin_addr.s_addr = INADDR_ANY; // Bind to all interfaces addr.sin_port = htons(port); // Convert port to network byte order // SO_REUSEADDR option to reuse the address int opt = 1; if (setsockopt(m_server_fd.get(), SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) { throw std::runtime_error("Failed to set socket options"); } // Bind the socket to the specified port if (bind(m_server_fd.get(), (sockaddr *)&addr, sizeof(addr)) < 0) { throw std::runtime_error("Failed to bind socket"); } if (listen(m_server_fd.get(), SOMAXCONN) < 0) { throw std::runtime_error("Failed to listen on socket"); } }