aboutsummaryrefslogtreecommitdiff
path: root/src/util/sock.cpp
diff options
context:
space:
mode:
authorVasil Dimov <vd@FreeBSD.org>2021-04-23 09:43:43 +0200
committerVasil Dimov <vd@FreeBSD.org>2021-12-01 15:22:08 +0100
commitf8bd13f85ae5404adef23a52719d804a5c36b1e8 (patch)
treeeca0fd0670339d479384bbed2ab6d0bbdd1444b9 /src/util/sock.cpp
parente7507f333bc93047d0baadea4fde19f770dacb56 (diff)
net: add new method Sock::Accept() that wraps accept()
This will help to increase `Sock` usage and make more code mockable.
Diffstat (limited to 'src/util/sock.cpp')
-rw-r--r--src/util/sock.cpp27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/util/sock.cpp b/src/util/sock.cpp
index 1a4d67a65e..2029d70a37 100644
--- a/src/util/sock.cpp
+++ b/src/util/sock.cpp
@@ -10,6 +10,7 @@
#include <util/system.h>
#include <util/time.h>
+#include <memory>
#include <stdexcept>
#include <string>
@@ -73,6 +74,32 @@ int Sock::Connect(const sockaddr* addr, socklen_t addr_len) const
return connect(m_socket, addr, addr_len);
}
+std::unique_ptr<Sock> Sock::Accept(sockaddr* addr, socklen_t* addr_len) const
+{
+#ifdef WIN32
+ static constexpr auto ERR = INVALID_SOCKET;
+#else
+ static constexpr auto ERR = SOCKET_ERROR;
+#endif
+
+ std::unique_ptr<Sock> sock;
+
+ const auto socket = accept(m_socket, addr, addr_len);
+ if (socket != ERR) {
+ try {
+ sock = std::make_unique<Sock>(socket);
+ } catch (const std::exception&) {
+#ifdef WIN32
+ closesocket(socket);
+#else
+ close(socket);
+#endif
+ }
+ }
+
+ return sock;
+}
+
int Sock::GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const
{
return getsockopt(m_socket, level, opt_name, static_cast<char*>(opt_val), opt_len);