From b0f65a02f2c5366de3e62da9f3dc6c04a89170d6 Mon Sep 17 00:00:00 2001 From: Veloman Yunkan Date: Sat, 18 Apr 2020 15:45:51 +0400 Subject: [PATCH] Server can be started on a random free port If the server is started with a port value of 0, it binds to a random free port. The bound port can be obtained with a `getPort()` method. --- include/server.h | 1 + src/server.cpp | 8 +++++++- test/server.cpp | 4 +++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/include/server.h b/include/server.h index b38ad8c04..599db91d1 100644 --- a/include/server.h +++ b/include/server.h @@ -53,6 +53,7 @@ namespace kiwix void setRoot(const std::string& root); void setAddress(const std::string& addr) { m_addr = addr; } void setPort(int port) { m_port = port; } + int getPort() const { return m_port; } void setNbThreads(int threads) { m_nbThreads = threads; } void setVerbose(bool verbose) { m_verbose = verbose; } void setTaskbar(bool withTaskbar, bool withLibraryButton) diff --git a/src/server.cpp b/src/server.cpp index 511a8936d..b01469a85 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -109,6 +109,8 @@ class InternalServer { bool start(); void stop(); + int getPort() const { return m_port; } + private: Response handle_request(const RequestContext& request); Response build_500(const std::string& msg); @@ -162,7 +164,9 @@ bool Server::start() { m_withTaskbar, m_withLibraryButton, m_blockExternalLinks)); - return mp_server->start(); + auto s = mp_server->start(); + m_port = mp_server->getPort(); + return s; } void Server::stop() { @@ -245,6 +249,8 @@ bool InternalServer::start() { << std::endl; return false; } + if (m_port == 0) + m_port = MHD_get_daemon_info(mp_daemon, MHD_DAEMON_INFO_BIND_PORT)->port; return true; } diff --git a/test/server.cpp b/test/server.cpp index 58c8450d5..43fdd9caf 100644 --- a/test/server.cpp +++ b/test/server.cpp @@ -50,6 +50,8 @@ ZimFileServer::ZimFileServer(int serverPort, std::string zimpath) if ( !server->start() ) throw std::runtime_error("ZimFileServer failed to start"); + if ( serverPort == 0 ) + serverPort = server->getPort(); client.reset(new httplib::Client(address, serverPort)); } @@ -64,7 +66,7 @@ class ServerTest : public ::testing::Test protected: std::unique_ptr zfs1_; - const int PORT = 8001; + const int PORT = 0; const std::string ZIMFILE = "./test/zimfile.zim"; protected: