jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
ScopedBlockingMode.hpp
Go to the documentation of this file.
1#pragma once
2
3#ifdef _WIN32
4#include <winsock2.h>
5#include <ws2tcpip.h>
6#else
7#include <fcntl.h>
8#include <sys/socket.h>
9#include <sys/types.h>
10#include <unistd.h>
11#endif
12
13#include <stdexcept>
14
36namespace jsocketpp::internal
37{
38
77{
78 public:
102 ScopedBlockingMode(const SOCKET sock, bool temporaryNonBlocking) : _sock(sock)
103 {
104#ifdef _WIN32
105 u_long mode = 0;
106 if (ioctlsocket(_sock, FIONBIO, &mode) == SOCKET_ERROR)
107 throw std::runtime_error("Failed to get socket mode");
108
109 _wasBlocking = (mode == 0);
110#else
111 const int flags = fcntl(_sock, F_GETFL, 0);
112 if (flags == -1)
113 throw std::runtime_error("Failed to get socket flags");
114
115 _wasBlocking = !(flags & O_NONBLOCK);
116#endif
117
118 if (_wasBlocking == temporaryNonBlocking)
119 {
120#ifdef _WIN32
121 u_long newMode = temporaryNonBlocking ? 1 : 0;
122 if (ioctlsocket(_sock, FIONBIO, &newMode) == SOCKET_ERROR)
123 throw std::runtime_error("Failed to set socket mode");
124#else
125 if (const int newFlags = temporaryNonBlocking ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
126 fcntl(_sock, F_SETFL, newFlags) == -1)
127 throw std::runtime_error("Failed to set socket mode");
128#endif
129 }
130 }
131
155 {
156 try
157 {
158#ifdef _WIN32
159 u_long mode = _wasBlocking ? 0 : 1;
160 ioctlsocket(_sock, FIONBIO, &mode);
161#else
162 if (const int flags = fcntl(_sock, F_GETFL, 0); flags != -1)
163 {
164 const int newFlags = _wasBlocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
165 fcntl(_sock, F_SETFL, newFlags);
166 }
167#endif
168 }
169 catch (...)
170 {
171 // Swallow exceptions in destructor
172 }
173 }
174
175 private:
178};
179
180} // namespace jsocketpp::internal
SOCKET _sock
Socket descriptor being managed for temporary mode override.
Definition ScopedBlockingMode.hpp:176
bool _wasBlocking
Whether the socket was originally in blocking mode.
Definition ScopedBlockingMode.hpp:177
~ScopedBlockingMode()
Restore the socket's original blocking mode on destruction.
Definition ScopedBlockingMode.hpp:154
ScopedBlockingMode(const SOCKET sock, bool temporaryNonBlocking)
Construct a ScopedBlockingMode that temporarily overrides the socket's blocking mode.
Definition ScopedBlockingMode.hpp:102
Implementation-only utilities and platform abstractions for jsocketpp.
Definition BufferView.hpp:49
int ioctlsocket(const SOCKET fd, const long cmd, u_long *argp)
Definition common.hpp:243
int SOCKET
Definition common.hpp:219
constexpr SOCKET SOCKET_ERROR
Definition common.hpp:221