jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
UnixSocket.hpp
Go to the documentation of this file.
1
5
6#pragma once
7
8#include "common.hpp"
9
10#include <string_view>
11
12// Enable AF_UNIX support on Windows 10+ (version 1803, build 17134) only
13#if defined(_MSC_VER) && (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
14// https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/
15#include <afunix.h> // Windows 10+ AF_UNIX support
16#define AF_UNIX 1
17#endif
18
19#include "common.hpp"
20#include "SocketException.hpp"
21#include "SocketOptions.hpp"
22
23namespace jsocketpp
24{
25
26#if defined(_WIN32) && defined(AF_UNIX) || defined(__unix__) || defined(__APPLE__)
27
88{
89 public:
95 explicit UnixSocket(std::string_view path, std::size_t bufferSize = 512);
96
100 UnixSocket(const UnixSocket&) = delete;
101
105 UnixSocket& operator=(const UnixSocket&) = delete;
106
111 UnixSocket(UnixSocket&& rhs) noexcept;
112
118 UnixSocket& operator=(UnixSocket&& rhs) noexcept;
119
125 ~UnixSocket() noexcept override;
126
131 void bind();
132
141 void listen(int backlog = SOMAXCONN) const;
142
148 [[nodiscard]] UnixSocket accept() const;
149
154 void connect();
155
162 [[nodiscard]] size_t write(std::string_view data) const;
163
171 size_t read(char* buffer, std::size_t len) const;
172
179 template <typename T> T read()
180 {
181 static_assert(std::is_trivially_copyable_v<T>, "UnixSocket::read<T>() only supports trivially copyable types");
182 T value;
183 const int len = ::recv(getSocketFd(), reinterpret_cast<char*>(&value),
184#ifdef _WIN32
185 static_cast<int>(sizeof(T)),
186#else
187 sizeof(T),
188#endif
189 0);
190 if (len == SOCKET_ERROR)
191 {
192 const int error = GetSocketError();
193 throw SocketException(error, SocketErrorMessage(error));
194 }
195 if (len == 0)
196 throw SocketException("Connection closed by remote socket.");
197 return value;
198 }
199
203 void close();
204
209 [[nodiscard]] bool isValid() const { return getSocketFd() != INVALID_SOCKET; }
210
215 [[nodiscard]] std::string getSocketPath() const { return this->_socketPath; }
216
226 void setNonBlocking(bool nonBlocking) const;
227
232 void setTimeout(int millis) const;
233
244 static bool isPathInUse(std::string_view path);
245
246 protected:
251
252 private:
253 bool _isListening = false;
254 std::string _socketPath{};
256 std::vector<char> _internalBuffer;
257};
258
270template <> inline std::string UnixSocket::read()
271{
272 const auto len = static_cast<int>(recv(getSocketFd(), _internalBuffer.data(),
273#ifdef _WIN32
274 static_cast<int>(_internalBuffer.size()),
275#else
276 _internalBuffer.size(),
277#endif
278 0));
279 if (len == SOCKET_ERROR)
280 {
281 const int error = GetSocketError();
282 throw SocketException(error, SocketErrorMessage(error));
283 }
284 if (len == 0)
285 throw SocketException("Connection closed by remote socket.");
286 return {_internalBuffer.data(), static_cast<size_t>(len)};
287}
288
289#endif
290
291} // namespace jsocketpp
Exception class for socket-related errors in jsocketpp.
Defines the SocketOptions base class for cross-platform socket option access.
Represents socket-related errors in the jsocketpp library.
Definition SocketException.hpp:63
SOCKADDR_UN _addr
Address structure for Unix domain sockets.
Definition UnixSocket.hpp:255
static bool isPathInUse(std::string_view path)
Checks whether a UNIX domain socket path is currently in use (i.e., a process is listening on it).
Definition UnixSocket.cpp:232
UnixSocket & operator=(const UnixSocket &)=delete
Copy assignment operator deleted to prevent copying.
void bind()
Binds the socket.
Definition UnixSocket.cpp:79
std::string _socketPath
Path for the Unix domain socket.
Definition UnixSocket.hpp:254
void close()
Closes the socket.
Definition UnixSocket.cpp:119
UnixSocket(std::string_view path, std::size_t bufferSize=512)
Constructs a UnixSocket and connects or binds to the specified path.
Definition UnixSocket.cpp:8
UnixSocket()
Default constructor for internal use (e.g., accept()).
Definition UnixSocket.hpp:250
void setTimeout(int millis) const
Sets a timeout for socket operations.
Definition UnixSocket.cpp:209
T read()
Reads a trivially copyable type from the socket.
Definition UnixSocket.hpp:179
void connect()
Connects the socket.
Definition UnixSocket.cpp:109
bool _isListening
True if the socket is listening for connections.
Definition UnixSocket.hpp:253
std::string getSocketPath() const
Returns the path of the Unix domain socket.
Definition UnixSocket.hpp:215
size_t read(char *buffer, std::size_t len) const
Reads data from the socket into a buffer.
Definition UnixSocket.cpp:163
void listen(int backlog=SOMAXCONN) const
Marks the socket as a passive socket to accept incoming connections.
Definition UnixSocket.cpp:99
std::vector< char > _internalBuffer
Internal buffer for read operations.
Definition UnixSocket.hpp:256
void setNonBlocking(bool nonBlocking) const
Sets the socket to non-blocking or blocking mode.
Definition UnixSocket.cpp:181
size_t write(std::string_view data) const
Writes data to the socket.
Definition UnixSocket.cpp:145
~UnixSocket() noexcept override
Destructor.
Definition UnixSocket.cpp:28
bool isValid() const
Checks if the socket is valid (open).
Definition UnixSocket.hpp:209
UnixSocket accept() const
Accepts an incoming connection.
Definition UnixSocket.cpp:128
UnixSocket(const UnixSocket &)=delete
Copy constructor deleted to prevent copying.
Common platform and utility includes for jsocketpp.
SocketOptions()=delete
Default constructor (deleted) for SocketOptions base class.
SOCKET getSocketFd() const noexcept
Retrieves the native socket handle (file descriptor or OS-level handle).
Definition SocketOptions.hpp:275
A C++ socket library providing Java-style networking interfaces.
Definition BufferView.hpp:16
std::string SocketErrorMessage(int error, bool gaiStrerror=false)
Convert a socket-related error code to a human-readable message.
Definition common.cpp:5
constexpr SOCKET INVALID_SOCKET
Definition common.hpp:264
sockaddr_un SOCKADDR_UN
Definition common.hpp:266
int GetSocketError()
Definition common.hpp:246
constexpr SOCKET SOCKET_ERROR
Definition common.hpp:265