From 72b35befb2421e69f0ba7de8859ad7036b4245a2 Mon Sep 17 00:00:00 2001 From: Piotr Date: Tue, 25 Mar 2025 00:14:24 +0100 Subject: [PATCH] Add AF_UNIX support on windows (#2115) Signed-off-by: Piotr Stankiewicz --- httplib.h | 11 +++++++++-- test/test.cc | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/httplib.h b/httplib.h index 836618f..1f06f77 100644 --- a/httplib.h +++ b/httplib.h @@ -187,6 +187,7 @@ using ssize_t = long; #include #include #include +#include #ifndef WSA_FLAG_NO_HANDLE_INHERIT #define WSA_FLAG_NO_HANDLE_INHERIT 0x80 @@ -3538,7 +3539,6 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, hints.ai_flags = socket_flags; } -#ifndef _WIN32 if (hints.ai_family == AF_UNIX) { const auto addrlen = host.length(); if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; } @@ -3562,11 +3562,19 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, sizeof(addr) - sizeof(addr.sun_path) + addrlen); #ifndef SOCK_CLOEXEC +#ifndef _WIN32 fcntl(sock, F_SETFD, FD_CLOEXEC); +#endif #endif if (socket_options) { socket_options(sock); } +#ifdef _WIN32 + // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so avoid + // setting default_socket_options. + detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0); +#endif + bool dummy; if (!bind_or_connect(sock, hints, dummy)) { close_socket(sock); @@ -3575,7 +3583,6 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, } return sock; } -#endif auto service = std::to_string(port); diff --git a/test/test.cc b/test/test.cc index acbd11a..7100ebc 100644 --- a/test/test.cc +++ b/test/test.cc @@ -70,7 +70,6 @@ static void read_file(const std::string &path, std::string &out) { fs.read(&out[0], static_cast(size)); } -#ifndef _WIN32 class UnixSocketTest : public ::testing::Test { protected: void TearDown() override { std::remove(pathname_.c_str()); } @@ -167,6 +166,7 @@ TEST_F(UnixSocketTest, abstract) { } #endif +#ifndef _WIN32 TEST(SocketStream, wait_writable_UNIX) { int fds[2]; ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));