From f275352cba8a6cd91f408ac26d75ab2eb323e209 Mon Sep 17 00:00:00 2001 From: Scott Graham Date: Tue, 29 May 2018 12:59:13 -0700 Subject: [PATCH] Handle port==0 when socket is bound on ipv6 I discovered https://github.com/yhirose/cpp-httplib/commit/0515c6aad6834a2a329db226b9312294d0002a13 doesn't work when the server is bound on an AF_INET6 address on Windows due to the getsockname() call failing. --- httplib.h | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/httplib.h b/httplib.h index e76f390..4420144 100644 --- a/httplib.h +++ b/httplib.h @@ -1626,12 +1626,18 @@ inline int Server::bind_internal(const char* host, int port, int socket_flags) } if (port == 0) { - struct sockaddr_in sin; - socklen_t len = sizeof(sin); - if (getsockname(svr_sock_, reinterpret_cast(&sin), &len) == -1) { + struct sockaddr_storage address; + socklen_t len = sizeof(address); + if (getsockname(svr_sock_, reinterpret_cast(&address), &len) == -1) { return -1; } - return ntohs(sin.sin_port); + if (address.ss_family == AF_INET) { + return ntohs(reinterpret_cast(&address)->sin_port); + } else if (address.ss_family == AF_INET6) { + return ntohs(reinterpret_cast(&address)->sin6_port); + } else { + return -1; + } } else { return port; }