jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches

Cross-platform abstraction for Unix domain sockets. More...

#include <UnixSocket.hpp>

Public Member Functions

 UnixSocket (std::string_view path, std::size_t bufferSize=512)
 Constructs a UnixSocket and connects or binds to the specified path.
 UnixSocket (const UnixSocket &)=delete
 Copy constructor deleted to prevent copying.
UnixSocketoperator= (const UnixSocket &)=delete
 Copy assignment operator deleted to prevent copying.
 UnixSocket (UnixSocket &&other) noexcept
 Move constructor transfers ownership of socket resources.
UnixSocketoperator= (UnixSocket &&other) noexcept
 Move assignment operator transfers ownership of socket resources.
 ~UnixSocket () noexcept
 Destructor.
void bind ()
 Binds the socket.
void listen (int backlog=SOMAXCONN) const
 Marks the socket as a passive socket to accept incoming connections.
UnixSocket accept () const
 Accepts an incoming connection.
void connect ()
 Connects the socket.
size_t write (std::string_view data) const
 Writes data to the socket.
size_t read (char *buffer, std::size_t len) const
 Reads data from the socket into a buffer.
template<typename T>
read ()
 Reads a trivially copyable type from the socket.
void close ()
 Closes the socket.
bool isValid () const
 Checks if the socket is valid (open).
std::string getSocketPath () const
 Returns the path of the Unix domain socket.
void setNonBlocking (bool nonBlocking) const
 Sets the socket to non-blocking or blocking mode.
void setTimeout (int millis) const
 Sets a timeout for socket operations.
void setOption (int level, int optName, int value) const
 Set a socket option on the Unix domain socket.
int getOption (int level, int optName) const
 Retrieve the value of a socket option for the Unix domain socket.
template<>
std::string read ()
 Template specialization to read a string from the Unix domain socket.

Static Public Member Functions

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).

Protected Member Functions

 UnixSocket ()
 Default constructor for internal use (e.g., accept()).

Private Attributes

SOCKET _sockFd = INVALID_SOCKET
 Underlying socket file descriptor.
bool _isListening = false
 True if the socket is listening for connections.
std::string _socketPath
 Path for the Unix domain socket.
SOCKADDR_UN _addr {}
 Address structure for Unix domain sockets.
std::vector< char > _buffer
 Internal buffer for read operations.

Detailed Description

Cross-platform abstraction for Unix domain sockets.

The UnixSocket class provides a convenient, modern C++20-style interface for using Unix domain sockets, also known as AF_UNIX sockets. Unix sockets are used for fast inter-process communication (IPC) on the same host, and use a file path on the local file system for addressing.

On POSIX platforms (Linux, macOS), AF_UNIX sockets are widely supported. On Windows, support is available in Windows 10 (1803+, build 17134) and newer.

Main Features

  • Bind: Create and bind a socket to a filesystem path for listening/accepting connections.
  • Listen/Accept: Wait for incoming connections and accept them (server-side).
  • Connect: Connect to a Unix domain socket path (client-side).
  • Read/Write: Send and receive data over the connection, supporting both binary and string types.
  • Non-blocking & Timeout: Support for non-blocking I/O and operation timeouts.
  • Automatic cleanup: Unlinks the socket file on destruction.
Note
Not thread-safe. Each UnixSocket should only be used from one thread at a time.
On Windows, AF_UNIX is supported on Windows 10 1803 and later only. On unsupported platforms, attempting to use this class will result in a compilation error.

Example: Simple Echo Server

using namespace jsocketpp;
int main() {
UnixSocket server("/tmp/echo.sock");
server.bind();
server.listen();
while (true) {
UnixSocket client = server.accept();
std::string data = client.read<std::string>();
client.write(data); // Echo back
}
}
Unix domain socket abstraction for jsocketpp.
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
size_t read(char *buffer, std::size_t len) const
Reads data from the socket into a buffer.
Definition UnixSocket.cpp:151
size_t write(std::string_view data) const
Writes data to the socket.
Definition UnixSocket.cpp:136
int main()
Definition client.cpp:89
A C++ socket library providing Java-style networking interfaces.
Definition BufferView.hpp:13

Example: Simple Client

using namespace jsocketpp;
int main() {
UnixSocket sock("/tmp/echo.sock");
sock.connect();
sock.write("Hello, Unix domain socket!");
std::string response = sock.read<std::string>();
}

Limitations

  • Not suitable for remote (network) connections; only for IPC on the same host.
  • The socket file is automatically deleted on destruction.

Constructor & Destructor Documentation

◆ UnixSocket() [1/4]

UnixSocket::UnixSocket ( std::string_view path,
std::size_t bufferSize = 512 )
explicit

Constructs a UnixSocket and connects or binds to the specified path.

Parameters
pathThe filesystem path for the Unix domain socket.
bufferSizeSize of the internal read buffer (default: 512).

◆ UnixSocket() [2/4]

jsocketpp::UnixSocket::UnixSocket ( const UnixSocket & )
delete

Copy constructor deleted to prevent copying.

◆ UnixSocket() [3/4]

UnixSocket::UnixSocket ( UnixSocket && other)
noexcept

Move constructor transfers ownership of socket resources.

Parameters
otherThe UnixSocket to move from.

◆ ~UnixSocket()

UnixSocket::~UnixSocket ( )
noexcept

Destructor.

Closes the socket if it is open.

◆ UnixSocket() [4/4]

jsocketpp::UnixSocket::UnixSocket ( )
inlineprotected

Default constructor for internal use (e.g., accept()).

Member Function Documentation

◆ accept()

UnixSocket UnixSocket::accept ( ) const

Accepts an incoming connection.

Returns
A new UnixSocket representing the accepted connection.
Exceptions
std::socket_exceptionif accept fails.

◆ bind()

void UnixSocket::bind ( )

Binds the socket.

Exceptions
std::socket_exceptionif binding fails.

◆ close()

void UnixSocket::close ( )

Closes the socket.

◆ connect()

void UnixSocket::connect ( )

Connects the socket.

Exceptions
std::socket_exceptionif connection fails.

◆ getOption()

int UnixSocket::getOption ( int level,
int optName ) const
nodiscard

Retrieve the value of a socket option for the Unix domain socket.

Parameters
levelThe protocol level (e.g., SOL_SOCKET).
optNameThe option name (e.g., SO_RCVBUF, SO_PASSCRED).
Returns
The value of the option.
Exceptions
SocketExceptionif the operation fails.

Example:

int bufSize = unixSocket.getOption(SOL_SOCKET, SO_RCVBUF);

◆ getSocketPath()

std::string jsocketpp::UnixSocket::getSocketPath ( ) const
inlinenodiscard

Returns the path of the Unix domain socket.

Returns
String containing the filesystem path of the socket.

◆ isPathInUse()

bool UnixSocket::isPathInUse ( std::string_view path)
static

Checks whether a UNIX domain socket path is currently in use (i.e., a process is listening on it).

This function attempts to connect to the given UNIX socket path. If the connection succeeds, the path is in use. If the connection fails with ECONNREFUSED or ENOENT, the path is not in use (either no process is listening, or the file does not exist).

Parameters
pathThe UNIX socket file system path to check.
Returns
true if a process is listening on the socket at the given path, false otherwise.

◆ isValid()

bool jsocketpp::UnixSocket::isValid ( ) const
inlinenodiscard

Checks if the socket is valid (open).

Returns
true if the socket is valid, false otherwise.

◆ listen()

void UnixSocket::listen ( int backlog = SOMAXCONN) const

Marks the socket as a passive socket to accept incoming connections.

Parameters
backlogThe maximum length to which the queue of pending connections may grow.
Exceptions
std::socket_exceptionif listen fails.

The backlog parameter defines the maximum number of pending connections that can be queued up before connections are refused.

◆ operator=() [1/2]

UnixSocket & jsocketpp::UnixSocket::operator= ( const UnixSocket & )
delete

Copy assignment operator deleted to prevent copying.

◆ operator=() [2/2]

UnixSocket & UnixSocket::operator= ( UnixSocket && other)
noexcept

Move assignment operator transfers ownership of socket resources.

Parameters
otherThe UnixSocket to move from.
Returns
Reference to this UnixSocket.

◆ read() [1/3]

template<typename T>
T jsocketpp::UnixSocket::read ( )
inline

Reads a trivially copyable type from the socket.

Template Parameters
TType to read (must be trivially copyable).
Returns
Value of type T read from the socket.
Exceptions
SocketExceptionon error or disconnect.

◆ read() [2/3]

template<>
std::string jsocketpp::UnixSocket::read ( )
inline

Template specialization to read a string from the Unix domain socket.

Reads data from the socket into the internal buffer and returns it as a string. Uses the socket's internal buffer size (set via constructor) as the maximum read length. The actual returned string length may be shorter depending on how much data was received.

Returns
String containing the received data.
Exceptions
SocketExceptionIf a socket error occurs or the connection is closed by the remote peer.
See also
UnixSocket() To modify the maximum read length via bufferSize parameter.

◆ read() [3/3]

size_t UnixSocket::read ( char * buffer,
std::size_t len ) const

Reads data from the socket into a buffer.

Parameters
bufferPointer to the buffer to read data into.
lenMaximum number of bytes to read.
Returns
The number of bytes read.
Exceptions
std::socket_exceptionif reading fails.

◆ setNonBlocking()

void UnixSocket::setNonBlocking ( bool nonBlocking) const

Sets the socket to non-blocking or blocking mode.

This function configures the socket to operate in either non-blocking or blocking mode, depending on the value of the nonBlocking parameter. In non-blocking mode, socket operations will return immediately if they cannot be completed, rather than blocking the calling thread.

Parameters
nonBlockingIf true, sets the socket to non-blocking mode; if false, sets it to blocking mode.

◆ setOption()

void UnixSocket::setOption ( int level,
int optName,
int value ) const

Set a socket option on the Unix domain socket.

This method allows you to configure low-level behaviors of the Unix domain socket, such as buffer sizes, timeouts, or special features like SO_PASSCRED.

Note
Not all options available for TCP/UDP sockets are relevant for Unix domain sockets. See your platform’s setsockopt(2) manpage for details.
Parameters
levelThe protocol level (e.g., SOL_SOCKET).
optNameThe option name (e.g., SO_RCVBUF, SO_SNDBUF, SO_PASSCRED).
valueThe integer value to set.
Exceptions
SocketExceptionif the operation fails.

Example:

unixSocket.setOption(SOL_SOCKET, SO_SNDBUF, 65536);

◆ setTimeout()

void UnixSocket::setTimeout ( int millis) const

Sets a timeout for socket operations.

Parameters
millisTimeout in milliseconds.

◆ write()

size_t UnixSocket::write ( std::string_view data) const

Writes data to the socket.

Parameters
dataThe data to write.
Returns
The number of bytes written.
Exceptions
std::socket_exceptionif writing fails.

Member Data Documentation

◆ _addr

SOCKADDR_UN jsocketpp::UnixSocket::_addr {}
private

Address structure for Unix domain sockets.

◆ _buffer

std::vector<char> jsocketpp::UnixSocket::_buffer
private

Internal buffer for read operations.

◆ _isListening

bool jsocketpp::UnixSocket::_isListening = false
private

True if the socket is listening for connections.

◆ _socketPath

std::string jsocketpp::UnixSocket::_socketPath
private

Path for the Unix domain socket.

◆ _sockFd

SOCKET jsocketpp::UnixSocket::_sockFd = INVALID_SOCKET
private

Underlying socket file descriptor.


The documentation for this class was generated from the following files: