From 292f9a6c556392f3e01fd947c6b7a8b3fcb700da Mon Sep 17 00:00:00 2001 From: yhirose Date: Mon, 30 Jun 2025 21:14:58 -0400 Subject: [PATCH] Add CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO --- httplib.h | 20 +++++++++++++++----- test/Makefile | 2 +- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/httplib.h b/httplib.h index ad03015..e91eb56 100644 --- a/httplib.h +++ b/httplib.h @@ -278,13 +278,15 @@ using socket_t = int; #include #include +#if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) #if defined(__APPLE__) #include -#if TARGET_OS_OSX || TARGET_OS_IPHONE +#if TARGET_OS_OSX #include #include #endif #endif +#endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO #ifdef CPPHTTPLIB_OPENSSL_SUPPORT #ifdef _WIN32 @@ -302,14 +304,16 @@ using socket_t = int; #endif #endif // _WIN32 +#if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) #if defined(__APPLE__) -#if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) #include #if TARGET_OS_OSX +#include +#include #include -#endif // TARGET_OS_OSX -#endif // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN -#endif // ___APPLE__ +#endif +#endif +#endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO #include #include @@ -3383,6 +3387,7 @@ unescape_abstract_namespace_unix_domain(const std::string &s) { inline int getaddrinfo_with_timeout(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res, time_t timeout_sec) { +#ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO if (timeout_sec <= 0) { // No timeout specified, use standard getaddrinfo return getaddrinfo(node, service, hints, res); @@ -3690,6 +3695,10 @@ inline int getaddrinfo_with_timeout(const char *node, const char *service, return EAI_AGAIN; // Return timeout error } #endif +#else + (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo + return getaddrinfo(node, service, hints, res); +#endif } template @@ -3868,6 +3877,7 @@ inline bool bind_ip_address(socket_t sock, const std::string &host) { if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) { return false; } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); auto ret = false; diff --git a/test/Makefile b/test/Makefile index f04a138..d9e7f31 100644 --- a/test/Makefile +++ b/test/Makefile @@ -1,5 +1,5 @@ CXX = clang++ -CXXFLAGS = -g -std=c++11 -I. -Wall -Wextra -Wtype-limits -Wconversion -Wshadow $(EXTRA_CXXFLAGS) # -fno-exceptions -DCPPHTTPLIB_NO_EXCEPTIONS -fsanitize=address +CXXFLAGS = -g -std=c++11 -I. -Wall -Wextra -Wtype-limits -Wconversion -Wshadow $(EXTRA_CXXFLAGS) -DCPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO # -fno-exceptions -DCPPHTTPLIB_NO_EXCEPTIONS -fsanitize=address PREFIX ?= $(shell brew --prefix)