From 31ef04179f144d972f66306374aaa439b661e118 Mon Sep 17 00:00:00 2001 From: sgourdas Date: Mon, 23 Sep 2024 19:18:57 +0300 Subject: [PATCH] Add ip availability check in server start --- include/tools.h | 9 +++++++++ src/server/internalServer.cpp | 5 +++++ src/tools/networkTools.cpp | 12 ++++++++++++ 3 files changed, 26 insertions(+) diff --git a/include/tools.h b/include/tools.h index f68fe9cdf..5c6c2a58a 100644 --- a/include/tools.h +++ b/include/tools.h @@ -225,6 +225,15 @@ IpAddress getBestPublicIps(IpMode mode); */ std::string getBestPublicIp(); +/** Checks if IP address is available + * + * Check if the given IP address is configured on any network interface of the system + * + * @param addr the IP address to check. + * @return true if the IP address is available on the system. + */ +bool ipAvailable(const IpAddress& addr); + /** Converts file size to human readable format. * * This function will convert a number to its equivalent size using units. diff --git a/src/server/internalServer.cpp b/src/server/internalServer.cpp index de20f73cc..800275bb8 100644 --- a/src/server/internalServer.cpp +++ b/src/server/internalServer.cpp @@ -474,6 +474,11 @@ bool InternalServer::start() { std::cerr << "IP address " << addr << " is not valid" << std::endl; return false; } + + if (!ipAvailable(m_addr)) { + std::cerr << "IP address " << (m_addr.addr.empty() ? m_addr.addr6 : m_addr.addr) << " is not available on this system" << std::endl; + return false; + } } if (m_ipMode == IpMode::ALL) { diff --git a/src/tools/networkTools.cpp b/src/tools/networkTools.cpp index 152802b5d..e55afde16 100644 --- a/src/tools/networkTools.cpp +++ b/src/tools/networkTools.cpp @@ -246,4 +246,16 @@ std::string getBestPublicIp() return getBestPublicIps(IpMode::ipv4).addr; } +bool ipAvailable(const IpAddress& addr) +{ + auto interfaces = kiwix::getNetworkInterfacesIPv4Or6(); + for (const auto& interface : interfaces) { + IpAddress interfaceIps = interface.second; + if (!interfaceIps.addr.empty() && interfaceIps.addr == addr.addr) return true; + if (!interfaceIps.addr6.empty() && interfaceIps.addr6 == addr.addr6) return true; + } + + return false; +} + } // namespace kiwix