Programming Tips - C/C++: start the civetweb webserver on a custom port

Date: 2025apr25 Library: civetweb Language: C/C++ Q. C/C++: start the civetweb webserver on a custom port A.
#include <string> #include "civetweb/include/civetweb.h" typedef struct mg_context *Context; // Returns a running context or nullptr Context startWebServer(const int port) { mg_init_library(0); mg_callbacks *callbacks = nullptr; void *userData = nullptr; if (port < 1024) { fprintf(stderr, "Can not use privileged port %d\n", port); return nullptr; } const std::string strPort = std::to_string(port); const char *options[] = { "listening_ports", strPort.c_str(), nullptr }; Context ctx = mg_start(callbacks, userData, options); if (ctx == nullptr) { fprintf(stderr, "Could not init webserver\n"); return nullptr; } printf("WebServer started\n"); return ctx; }