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

A C++ socket library providing Java-style networking interfaces. More...

Namespaces

namespace  internal
 Implementation-only utilities and platform abstractions for jsocketpp.
namespace  net
 Endianness utilities for network byte order conversion.
namespace  detail
 Implementation details and type traits for jsocketpp buffer management.

Classes

struct  BufferView
 Represents a raw writable memory region for scatter/gather I/O. More...
class  DatagramPacket
 Represents a UDP datagram packet, encapsulating both payload and addressing information. More...
struct  DatagramReadOptions
 Options controlling a single UDP receive operation. More...
struct  DatagramReadResult
 Telemetry data about a single UDP datagram receive operation. More...
struct  ReadExactOptions
 Policy for enforcing an exact-byte receive on a single UDP datagram. More...
class  DatagramSocket
 Cross-platform UDP socket class with Java-style interface. More...
class  MulticastSocket
 Cross-platform multicast UDP socket class (IPv4/IPv6). More...
class  ServerSocket
 TCP server socket abstraction for cross-platform C++ networking. More...
class  Socket
 TCP client connection abstraction (Java-like interface). More...
class  SocketException
 Represents socket-related errors in the jsocketpp library. More...
class  SocketInitializer
 Helper class to initialize and cleanup sockets (RAII). More...
class  SocketOptions
 Public base class for raw socket option access via setsockopt() and getsockopt(). More...
class  SocketTimeoutException
 Exception class for socket operations that time out. More...
class  UnixSocket
 Cross-platform abstraction for Unix domain sockets. More...

Typedefs

typedef long ssize_t
typedef int SOCKET
typedef sockaddr_un SOCKADDR_UN
using Port = std::uint16_t
 Type alias representing a TCP or UDP port number (1–65535).

Enumerations

enum class  ShutdownMode { Read , Write , Both }
 Enum for socket shutdown modes. More...
enum class  DatagramReceiveMode : std::uint8_t { DatagramReceiveMode::NoPreflight = 0 , DatagramReceiveMode::PreflightSize = 1 , DatagramReceiveMode::PreflightMax = 2 }
 Receive-time sizing policy for UDP datagrams. More...
enum class  Direction : std::uint8_t { Direction::Read , Direction::Write , Direction::ReadWrite }
 I/O readiness selector used by waitReady(). More...

Functions

int InitSockets ()
int CleanupSockets ()
int GetSocketError ()
int CloseSocket (SOCKET fd)
const char * inet_ntop_aux (int af, const void *src, char *dst, socklen_t size)
int ioctlsocket (const SOCKET fd, const long cmd, u_long *argp)
std::vector< std::string > getHostAddr ()
 Get all local network interface addresses as strings.
std::string SocketErrorMessage (int error, bool gaiStrerror=false)
 Convert a socket-related error code to a human-readable message.
bool isIPv4MappedIPv6 (const sockaddr_in6 *addr6)
 Checks if a given sockaddr_in6 represents an IPv4-mapped IPv6 address.
sockaddr_in convertIPv4MappedIPv6ToIPv4 (const sockaddr_in6 &addr6)
 Converts an IPv4-mapped IPv6 address to a pure IPv4 sockaddr_in.
std::string ipFromSockaddr (const sockaddr *addr, bool convertIPv4Mapped=true)
 Extracts a human-readable IP address from a socket address structure.
Port portFromSockaddr (const sockaddr *addr)
 Extracts the port number from a socket address structure.
std::string addressToString (const sockaddr_storage &addr)
 Converts a socket address to a human-readable "IP:port" string.
void stringToAddress (const std::string &str, sockaddr_storage &addr)
 Parses an "IP:port" string into a sockaddr_storage structure.

Variables

constexpr SOCKET INVALID_SOCKET = -1
constexpr SOCKET SOCKET_ERROR = -1
constexpr std::size_t DefaultBufferSize = 4096
 Default internal buffer size (in bytes) for socket read operations.
constexpr std::size_t DefaultDatagramReceiveSize = 8192
 Fallback receive size (in bytes) for UDP datagrams when the exact size is unknown.
constexpr std::size_t MaxDatagramPayloadSafe = 65507
 Maximum UDP payload size (in bytes) that is safely valid across common stacks.
constexpr std::size_t MaxUdpPayloadIPv4 = 65507
 Maximum UDP payload size (in bytes) over IPv4.
constexpr std::size_t MaxUdpPayloadIPv6 = 65527
 Theoretical maximum UDP payload size (in bytes) over IPv6.

Detailed Description

A C++ socket library providing Java-style networking interfaces.

The jsocketpp namespace contains classes and utilities for network programming with an API design inspired by Java's networking classes. It provides:

Core Socket Classes:

  • Socket: TCP client socket implementation for stream-based communication
  • ServerSocket: TCP server socket for accepting client connections
  • DatagramSocket: UDP socket implementation for connectionless communication
  • MulticastSocket: Extended UDP socket supporting IP multicast operations
  • UnixSocket: Unix domain socket implementation for local IPC

Features:

  • Exception-based error handling (SocketException)
  • RAII-compliant resource management
  • Support for both IPv4 and IPv6
  • Cross-platform compatibility (Windows/Unix)
  • Modern C++ design with move semantics

Design Philosophy:

  • Familiar interface for Java developers
  • Modern C++ practices and idioms
  • Exception-based error handling
  • Resource safety through RAII
  • Explicit over implicit behavior
Note
All classes in this namespace are not thread-safe unless explicitly stated. Each socket should be used from a single thread at a time.

Typedef Documentation

◆ SOCKADDR_UN

typedef sockaddr_un jsocketpp::SOCKADDR_UN

◆ SOCKET

typedef int jsocketpp::SOCKET

◆ ssize_t

typedef long jsocketpp::ssize_t

Enumeration Type Documentation

◆ ShutdownMode

enum class jsocketpp::ShutdownMode
strong

Enum for socket shutdown modes.

Used to specify how to shutdown a socket (read, write, or both).

Enumerator
Read 

Shutdown read operations (SHUT_RD or SD_RECEIVE).

Write 

Shutdown write operations (SHUT_WR or SD_SEND).

Both 

Shutdown both read and write operations (SHUT_RDWR or SD_BOTH).

Function Documentation

◆ CleanupSockets()

int jsocketpp::CleanupSockets ( )
inlineconstexpr

◆ CloseSocket()

int jsocketpp::CloseSocket ( SOCKET fd)
inline

◆ getHostAddr()

std::vector< std::string > jsocketpp::getHostAddr ( )

Get all local network interface addresses as strings.

Returns
Vector of strings describing each interface and address.

◆ GetSocketError()

int jsocketpp::GetSocketError ( )
inline

◆ inet_ntop_aux()

const char * jsocketpp::inet_ntop_aux ( int af,
const void * src,
char * dst,
socklen_t size )

◆ InitSockets()

int jsocketpp::InitSockets ( )
inlineconstexpr

◆ ioctlsocket()

int jsocketpp::ioctlsocket ( const SOCKET fd,
const long cmd,
u_long * argp )
inline

◆ ipFromSockaddr()

std::string jsocketpp::ipFromSockaddr ( const sockaddr * addr,
bool convertIPv4Mapped = true )

Extracts a human-readable IP address from a socket address structure.

This function returns the numeric IP address (IPv4 or IPv6) contained in the given sockaddr. If the address is an IPv4-mapped IPv6 (::ffff:a.b.c.d) and convertIPv4Mapped is true, the result is converted to the original IPv4 form (e.g., "192.168.1.10").

Parameters
addrPointer to a sockaddr structure (must be AF_INET or AF_INET6).
convertIPv4MappedWhether to convert IPv4-mapped IPv6 addresses to plain IPv4.
Returns
IP address as a string (e.g., "127.0.0.1" or "fe80::1").
Exceptions
SocketExceptionif the address family is unsupported or conversion fails.

◆ portFromSockaddr()

Port jsocketpp::portFromSockaddr ( const sockaddr * addr)

Extracts the port number from a socket address structure.

Retrieves the port from a sockaddr containing either an IPv4 or IPv6 address, converting it from network byte order to host byte order.

Parameters
addrPointer to a sockaddr structure (must be AF_INET or AF_INET6).
Returns
Port number in host byte order (e.g., 8080).
Exceptions
SocketExceptionif the address family is unsupported.

◆ SocketErrorMessage()

std::string jsocketpp::SocketErrorMessage ( int error,
bool gaiStrerror = false )

Convert a socket-related error code to a human-readable message.

This helper produces best-effort, descriptive text for errors originating from:

  • Traditional socket/Winsock APIs that report failure via errno or WSAGetLastError().
  • Modern address APIs (getaddrinfo/getnameinfo) that return EAI_* codes directly.

Usage rules:

  • For APIs that set errno or WSAGetLastError(), pass that code with gaiStrerror set to false.
  • For getaddrinfo/getnameinfo failures, pass the function's return value with gaiStrerror set to true. Do not call WSAGetLastError() for getaddrinfo/getnameinfo, as those functions return their error code.

Platform behavior:

  • Windows: Attempts FormatMessageA for system and WSA* codes; for EAI_* codes, uses gai_strerrorA. The returned text is trimmed of trailing newlines/spaces. Fallbacks include std::system_category().message() and strerror_s(). The function is written to avoid throwing; if resolution fails, it returns a generic message.
  • POSIX: Uses std::system_category().message() for errno values and gai_strerror() for EAI_* codes, falling back to strerror() when necessary. The function is written to avoid throwing.

Thread-safety notes:

  • The implementation copies any message obtained from gai_strerror/gai_strerrorA immediately into a std::string, avoiding reliance on static internal buffers after return.
Parameters
[in]errorNumeric error code. For errno/WSA* paths, pass errno or GetSocketError() (WSAGetLastError()). For getaddrinfo/getnameinfo, pass the function's non-zero return value (an EAI_* code).
[in]gaiStrerrorSet to true if error is an address-resolution error from getaddrinfo/getnameinfo (EAI_* domain). Set to false for traditional socket/Winsock errors (errno/WSA* domain). Default is false.
Returns
A best-effort, human-readable description of the error. Returns an empty string when error is zero.
Note
Some environments may produce localized messages. Message content is not guaranteed to be stable across operating systems, C libraries, or language settings.
Exceptions
Thisfunction is designed not to throw. In failure cases, it returns a conservative string such as "Unknown error <code>".
// Example: traditional socket/Winsock error
if (sendto(sock, buf, len, 0, addr, addrlen) == SOCKET_ERROR) {
const int err = GetSocketError(); // wraps WSAGetLastError() on Windows, errno elsewhere
std::string msg = SocketErrorMessage(err, false);
// handle or log 'msg'
}
// Example: getaddrinfo failure (EAI_* code)
addrinfo* ai = nullptr;
const int ret = ::getaddrinfo(host, service, &hints, &ai);
if (ret != 0) {
std::string msg = SocketErrorMessage(ret, true);
// handle or log 'msg'
}
std::string SocketErrorMessage(int error, bool gaiStrerror=false)
Convert a socket-related error code to a human-readable message.
Definition common.cpp:5
int GetSocketError()
Definition common.hpp:246
constexpr SOCKET SOCKET_ERROR
Definition common.hpp:265

Variable Documentation

◆ INVALID_SOCKET

SOCKET jsocketpp::INVALID_SOCKET = -1
constexpr

◆ SOCKET_ERROR

SOCKET jsocketpp::SOCKET_ERROR = -1
constexpr