jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
ScopedBlockingMode.hpp
Go to the documentation of this file.
1
8
9#pragma once
10
11#ifdef _WIN32
12#include <winsock2.h>
13#include <ws2tcpip.h>
14#else
15#include <fcntl.h>
16#include <sys/socket.h>
17#include <sys/types.h>
18#include <unistd.h>
19#endif
20
21#include <stdexcept>
22
44namespace jsocketpp::internal
45{
46
85{
86 public:
110 ScopedBlockingMode(const SOCKET sock, bool temporaryNonBlocking) : _sock(sock)
111 {
112#ifdef _WIN32
113 u_long mode = 0;
114 if (ioctlsocket(_sock, FIONBIO, &mode) == SOCKET_ERROR)
115 throw std::runtime_error("Failed to get socket mode");
116
117 _wasBlocking = (mode == 0);
118#else
119 const int flags = fcntl(_sock, F_GETFL, 0);
120 if (flags == -1)
121 throw std::runtime_error("Failed to get socket flags");
122
123 _wasBlocking = !(flags & O_NONBLOCK);
124#endif
125
126 if (_wasBlocking == temporaryNonBlocking)
127 {
128#ifdef _WIN32
129 u_long newMode = temporaryNonBlocking ? 1 : 0;
130 if (ioctlsocket(_sock, FIONBIO, &newMode) == SOCKET_ERROR)
131 throw std::runtime_error("Failed to set socket mode");
132#else
133 if (const int newFlags = temporaryNonBlocking ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
134 fcntl(_sock, F_SETFL, newFlags) == -1)
135 throw std::runtime_error("Failed to set socket mode");
136#endif
137 }
138 }
139
163 {
164 try
165 {
166#ifdef _WIN32
167 u_long mode = _wasBlocking ? 0 : 1;
168 ioctlsocket(_sock, FIONBIO, &mode);
169#else
170 if (const int flags = fcntl(_sock, F_GETFL, 0); flags != -1)
171 {
172 const int newFlags = _wasBlocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
173 fcntl(_sock, F_SETFL, newFlags);
174 }
175#endif
176 }
177 catch (...)
178 {
179 // Swallow exceptions in destructor
180 }
181 }
182
183 private:
186};
187
188} // namespace jsocketpp::internal
SOCKET _sock
Socket descriptor being managed for temporary mode override.
Definition ScopedBlockingMode.hpp:184
bool _wasBlocking
Whether the socket was originally in blocking mode.
Definition ScopedBlockingMode.hpp:185
~ScopedBlockingMode()
Restore the socket's original blocking mode on destruction.
Definition ScopedBlockingMode.hpp:162
ScopedBlockingMode(const SOCKET sock, bool temporaryNonBlocking)
Construct a ScopedBlockingMode that temporarily overrides the socket's blocking mode.
Definition ScopedBlockingMode.hpp:110
Implementation-only utilities and platform abstractions for jsocketpp.
Definition BufferView.hpp:52
int ioctlsocket(const SOCKET fd, const long cmd, u_long *argp)
Definition common.hpp:287
int SOCKET
Definition common.hpp:263
constexpr SOCKET SOCKET_ERROR
Definition common.hpp:265