#include #include #include #include #include #include #include const int PORT = 8089; std::string getHtmlPage(const std::string& path) { if (path == "/" || path == "/index") { return R"( C++ Webserver
C++ HTTP Server

🌐 Hallo, Welt!

Dieser Webserver wurde komplett in reinem C++ geschrieben — ohne externe Bibliotheken. Er nutzt direkt die POSIX Socket API des Betriebssystems.

)"; } else if (path == "/info") { return R"( Server Info

🔧 Server-Informationen

EigenschaftWert
SpracheC++ (ISO C++17)
BibliothekenNur POSIX Standard (sys/socket.h)
Port8080
ProtokollHTTP/1.0
PlattformLinux

← Zurück

)"; } else if (path == "/zeit") { time_t now = time(nullptr); std::string zeit = std::string(ctime(&now)); return "Zeit" "" "

🕐 Aktuelle Serverzeit

" + zeit + "

" "

← Zurück

"; } return R"( 404

404

Seite nicht gefunden.

Startseite

)"; } std::string buildResponse(const std::string& path) { std::string body = getHtmlPage(path); std::string status = (path == "/" || path == "/info" || path == "/zeit") ? "200 OK" : "404 Not Found"; std::ostringstream response; response << "HTTP/1.0 " << status << "\r\n" << "Content-Type: text/html; charset=UTF-8\r\n" << "Content-Length: " << body.size() << "\r\n" << "Connection: close\r\n" << "\r\n" << body; return response.str(); } int main() { int server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { std::cerr << "Socket-Fehler\n"; return 1; } int opt = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); sockaddr_in address{}; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); if (bind(server_fd, (sockaddr*)&address, sizeof(address)) < 0) { std::cerr << "Bind-Fehler\n"; return 1; } if (listen(server_fd, 10) < 0) { std::cerr << "Listen-Fehler\n"; return 1; } std::cout << "Server laeuft auf http://localhost:" << PORT << "\n"; std::cout << "Seiten: / /info /zeit\n"; std::cout << "Beenden mit Ctrl+C\n\n"; while (true) { int client_fd = accept(server_fd, nullptr, nullptr); if (client_fd < 0) continue; char buffer[4096] = {}; read(client_fd, buffer, sizeof(buffer) - 1); // HTTP-Anfrage parsen: "GET /path HTTP/1.x" std::string request(buffer); std::string path = "/"; size_t start = request.find(' '); if (start != std::string::npos) { size_t end = request.find(' ', start + 1); if (end != std::string::npos) path = request.substr(start + 1, end - start - 1); } std::cout << "Anfrage: " << path << "\n"; std::string response = buildResponse(path); send(client_fd, response.c_str(), response.size(), 0); close(client_fd); } close(server_fd); return 0; }