![]() |
jsocketpp 1.0
A cross-platform C++20 socket library.
|
Cross-platform multicast UDP socket class (IPv4/IPv6). More...
#include <MulticastSocket.hpp>


Public Member Functions | |
| MulticastSocket (Port localPort, std::string_view localAddress, std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, bool reuseAddress=true, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool nonBlocking=false, bool dualStack=true, bool autoBind=true) | |
| Constructs a fully configurable multicast socket for receiving and sending datagrams. | |
| void | joinGroup (const std::string &groupAddr, const std::string &iface) |
| Join a multicast group on an optional interface (string-friendly). | |
| void | leaveGroup (const std::string &groupAddr, const std::string &iface="") |
| Leave a multicast group on an optional interface (string-friendly). | |
| void | setMulticastInterface (const std::string &iface) |
| Select the default outgoing interface for multicast transmissions. | |
| std::string | getMulticastInterface () const |
| Get the currently selected egress interface for multicast transmissions. | |
| void | setTimeToLive (int ttl) |
| Set the time-to-live (TTL) / hop limit for outgoing multicast packets. | |
| int | getTimeToLive () const |
| Get the current default multicast TTL / hop limit cached on this socket. | |
| void | setLoopbackMode (bool enable) |
| Enable or disable multicast loopback for this socket. | |
| bool | getLoopbackMode () const |
| Get the current multicast loopback mode cached on this socket. | |
| std::string | getCurrentGroup () const |
| Returns the last multicast group joined (for reference/debug). | |
| Public Member Functions inherited from jsocketpp::DatagramSocket | |
| DatagramSocket (Port localPort=0, std::string_view localAddress="", std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, bool reuseAddress=true, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool nonBlocking=false, bool dualStack=true, bool autoBind=true, bool autoConnect=false, std::string_view remoteAddress="", Port remotePort=0, int connectTimeoutMillis=-1) | |
| Creates a UDP socket, optionally binds to a local address, and optionally connects to a remote peer. | |
| ~DatagramSocket () noexcept override | |
| Destructor for DatagramSocket. Ensures socket resources are released. | |
| DatagramSocket (const DatagramSocket &)=delete | |
| Copy constructor (deleted) for DatagramSocket. | |
| DatagramSocket & | operator= (const DatagramSocket &)=delete |
| Copy assignment operator (deleted) for DatagramSocket. | |
| DatagramSocket (DatagramSocket &&rhs) noexcept | |
| Move constructor for DatagramSocket. | |
| DatagramSocket & | operator= (DatagramSocket &&rhs) noexcept |
| Move assignment operator for DatagramSocket. | |
| void | bind () |
| Binds the datagram socket to all available interfaces on an ephemeral port. | |
| void | bind (Port localPort) |
| Binds the datagram socket to a specific local port on all network interfaces. | |
| void | bind (std::string_view localAddress, Port localPort) |
| Binds the datagram socket to a specific local IP address and port. | |
| bool | isBound () const noexcept |
| Indicates whether the datagram socket has been explicitly bound to a local address or port. | |
| void | connect (std::string_view host, Port port, int timeoutMillis) |
| Connect this UDP socket to a default peer (set the default destination). | |
| void | disconnect () |
| Disconnect this UDP socket from its current default peer. | |
| bool | isConnected () const noexcept |
| Indicates whether the datagram socket is connected to a specific remote peer. | |
| std::string | getLocalIp (bool convertIPv4Mapped) |
| Return the local interface IP address for this UDP socket. | |
| Port | getLocalPort () |
| Return the local UDP port this socket is bound to. | |
| std::string | getLocalSocketAddress (bool convertIPv4Mapped) |
| Return the local endpoint as a single "ip:port" string. | |
| std::string | getRemoteIp (bool convertIPv4Mapped) const |
| Return the remote peer IP address for this socket. | |
| Port | getRemotePort () const |
| Return the remote peer UDP port for this socket. | |
| std::string | getRemoteSocketAddress (bool convertIPv4Mapped) const |
| Return the remote endpoint as a single "ip:port" string. | |
| void | write (std::string_view message) const |
| Send one UDP datagram to the currently connected peer (no pre-wait). | |
| template<typename T> | |
| void | write (const T &value) const |
Send one UDP datagram whose payload is the raw object representation of value. | |
| void | write (std::span< const std::byte > data) const |
| Send one UDP datagram to the connected peer from a raw byte span (no pre-wait). | |
| void | writeAll (std::string_view message) const |
| Send one UDP datagram to the connected peer, waiting indefinitely for writability. | |
| template<typename T> | |
| void | writePrefixed (const std::string_view payload) const |
| Send a length-prefixed UDP datagram to the connected peer from text bytes (no pre-wait). | |
| template<typename T> | |
| void | writePrefixed (const std::span< const std::byte > payload) const |
| Send a length-prefixed UDP datagram to the connected peer from a byte span (no pre-wait). | |
| template<typename T> | |
| void | writePrefixedTo (const std::string_view host, const Port port, const std::string_view payload) const |
| Send a length-prefixed UDP datagram to (host, port) from text bytes (unconnected path). | |
| template<typename T> | |
| void | writePrefixedTo (const std::string_view host, const Port port, const std::span< const std::byte > payload) const |
| Send a length-prefixed UDP datagram to (host, port) from a byte span (unconnected path). | |
| void | writev (std::span< const std::string_view > buffers) const |
| Send one UDP datagram to the connected peer by concatenating multiple fragments (no pre-wait). | |
| void | writevAll (std::span< const std::string_view > buffers) const |
| Send one UDP datagram to the connected peer by concatenating multiple fragments, waiting indefinitely. | |
| void | writeFrom (const void *data, std::size_t len) const |
| Send one UDP datagram to the connected peer from a raw memory buffer (no pre-wait). | |
| void | writeWithTimeout (std::string_view data, int timeoutMillis) const |
Send one UDP datagram to the connected peer, waiting up to timeoutMillis for writability. | |
| void | write (const DatagramPacket &packet) |
| Send one UDP datagram using a packet’s buffer and optional explicit destination. | |
| void | writeTo (std::string_view host, Port port, std::string_view message) |
| Send one unconnected UDP datagram to (host, port) from text bytes (no pre-wait). | |
| void | writeTo (std::string_view host, Port port, std::span< const std::byte > data) |
| Send one unconnected UDP datagram to (host, port) from a raw byte span (no pre-wait). | |
| template<typename T> | |
| void | writeTo (const std::string_view host, const Port port, const T &value) const |
Send one unconnected UDP datagram to (host, port) containing the raw bytes of value. | |
| DatagramReadResult | read (DatagramPacket &packet, const DatagramReadOptions &opts) const |
| Read one UDP datagram into a DatagramPacket with optional growth/shrink and strict truncation policy. | |
| DatagramReadResult | readInto (void *buffer, std::size_t len, const DatagramReadOptions &opts={}) const |
| Read one UDP datagram into a caller-provided buffer with explicit truncation policy. | |
| DatagramReadResult | readInto (std::span< char > out, const DatagramReadOptions &opts={}) const |
| Read one UDP datagram into a caller-provided span (zero allocation) with explicit truncation policy. | |
| template<typename T, std::enable_if_t< detail::is_dynamic_buffer_v< T >, int > = 0> | |
| T | read (const DatagramReadOptions &opts={}, std::size_t minCapacity=DefaultDatagramReceiveSize) const |
| Read one UDP datagram into a dynamically resizable, contiguous byte container (zero-copy into caller storage). | |
| template<typename T, std::enable_if_t< detail::is_fixed_buffer_v< T >, int > = 0> | |
| T | read (const DatagramReadOptions &opts={}) const |
| Read one UDP datagram into a fixed-size, contiguous byte container (zero allocation). | |
| template<typename T> | |
| DatagramReadResult | readFrom (T &buffer, std::string *senderAddr, Port *senderPort, const DatagramReadOptions &opts) const |
| Read one UDP datagram into a caller-provided byte container and optionally return the sender address/port. | |
| DatagramReadResult | readExact (void *buffer, std::size_t exactLen, const ReadExactOptions &opts={}) const |
Receive exactly exactLen bytes from a single UDP datagram into buffer, with strict policy control. | |
| DatagramReadResult | readExact (std::span< char > out, const ReadExactOptions &opts={}) const |
Span overload of readExact(...) (derives exactLen from out.size()). | |
| template<typename T> | |
| DatagramReadResult | readExact (T &buffer, const std::size_t exactLen, const ReadExactOptions &opts={}) const |
Receive exactly exactLen bytes from a single UDP datagram into a contiguous byte container. | |
| std::size_t | readAtMost (std::span< char > out, const DatagramReadOptions &opts={}) const |
Read up to out.size() bytes from the next UDP datagram into a caller-provided buffer (no allocation). | |
| std::string | readAtMost (std::size_t n) const |
Read up to n bytes from the next UDP datagram and return them as a newly allocated string. | |
| std::string | readAvailable () const |
| Receive the next UDP datagram and return its payload as a string, attempting to avoid truncation. | |
| std::size_t | readAvailable (std::span< char > out, const DatagramReadOptions &opts={}) const |
| Receive the entire next UDP datagram into a caller-provided buffer, with explicit truncation policy. | |
| std::size_t | readIntoExact (void *buffer, std::size_t len) const |
| Strict exact-length UDP receive into a caller-provided buffer (single datagram). | |
| std::string | readAtMostWithTimeout (std::size_t n, int timeoutMillis) const |
Read up to n bytes from the next UDP datagram, waiting up to timeoutMillis for data. | |
| template<typename T, std::enable_if_t< std::is_integral_v< T > &&std::is_unsigned_v< T > &&std::is_trivially_copyable_v< T >, int > = 0> | |
| std::string | readPrefixed (std::size_t maxPayloadLen=MaxDatagramPayloadSafe, const std::endian prefixEndian=std::endian::big) const |
Read a length-prefixed UDP datagram and return the payload (prefix type T). | |
| void | discard (const DatagramReadOptions &opts={}) const |
| Discard the next UDP datagram without copying it out. | |
| void | discardExact (std::size_t n, const DatagramReadOptions &opts={}) const |
Discard the next UDP datagram only if its payload size is exactly n bytes. | |
| DatagramReadResult | readv (std::span< BufferView > buffers, const DatagramReadOptions &opts={}) const |
| Scatter-gather receive: read one UDP datagram into multiple non-contiguous buffers. | |
| DatagramReadResult | readvAll (std::span< BufferView > buffers, const DatagramReadOptions &opts={}) const |
| Scatter-gather receive that guarantees the entire next datagram fits the provided buffers. | |
| std::size_t | readvAllBytes (std::span< BufferView > buffers, const DatagramReadOptions &opts={}) const |
| Back-compat convenience returning only the number of bytes copied. | |
| DatagramReadResult | readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis, const DatagramReadOptions &opts={}) const |
| Scatter-gather, best-effort read of the next datagram with a per-call timeout. | |
| std::size_t | readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Convenience wrapper returning only the number of bytes read. | |
| DatagramReadResult | readvAllWithTotalTimeout (std::span< BufferView > buffers, int totalTimeoutMillis, const DatagramReadOptions &opts={}) const |
| Scatter-gather, strict no-truncation receive with a per-call total timeout. | |
| std::size_t | readvAllWithTotalTimeoutBytes (std::span< BufferView > buffers, int totalTimeoutMillis, const DatagramReadOptions &opts={}) const |
| Convenience wrapper returning only the number of bytes copied. | |
| DatagramReadResult | peek (DatagramPacket &packet, bool allowResize=true, const DatagramReadOptions &opts={}) const |
| Peek at the next UDP datagram without consuming it (single receive with MSG_PEEK). | |
| bool | hasPendingData (int timeoutMillis) const |
| Check if the socket is readable within a timeout (no data is consumed). | |
| std::optional< int > | getMTU () const |
| Retrieves the Maximum Transmission Unit (MTU) of the local interface associated with the socket. | |
| void | waitReady (Direction dir, int timeoutMillis) const |
| Block until the socket is ready for I/O or a timeout occurs. | |
| void | setInternalBufferSize (std::size_t newLen) |
| Sets the size of the internal buffer used for string-based UDP receive operations. | |
| void | close () |
| Closes the datagram socket and releases its underlying system resources. | |
| bool | isValid () const noexcept |
| Checks whether the datagram socket is valid and ready for use. | |
| bool | isClosed () const noexcept |
| Checks whether the datagram socket has been closed or is otherwise invalid. | |
| std::optional< std::pair< sockaddr_storage, socklen_t > > | getLastPeerSockAddr () const |
| Retrieves the raw socket address of the last known remote peer. | |
| Public Member Functions inherited from jsocketpp::SocketOptions | |
| SocketOptions ()=delete | |
| Default constructor (deleted) for SocketOptions base class. | |
| SocketOptions (const SOCKET sock) noexcept | |
| Initializes the socket option interface with a specific socket descriptor. | |
| virtual | ~SocketOptions ()=default |
| Virtual destructor for safe polymorphic destruction. | |
| SocketOptions (const SocketOptions &)=delete | |
| Copy constructor (deleted) for SocketOptions. | |
| SocketOptions (SocketOptions &&) noexcept=default | |
| Move constructor for SocketOptions. | |
| SocketOptions & | operator= (const SocketOptions &)=delete |
| Copy assignment operator (deleted) for SocketOptions. | |
| SocketOptions & | operator= (SocketOptions &&) noexcept=default |
| Move assignment operator for SocketOptions. | |
| SOCKET | getSocketFd () const noexcept |
| Retrieves the native socket handle (file descriptor or OS-level handle). | |
| void | setOption (int level, int optName, int value) |
| Sets a low-level socket option on the underlying socket. | |
| void | setOption (int level, int optName, const void *value, socklen_t len) |
| Sets a low-level socket option using a structured or binary value. | |
| int | getOption (int level, int optName) const |
| Retrieves the current value of a low-level socket option. | |
| void | getOption (int level, int optName, void *result, socklen_t *len) const |
| Retrieves a socket option into a structured or binary buffer. | |
| void | setReuseAddress (bool on) |
| Enables or disables the SO_REUSEADDR socket option. | |
| bool | getReuseAddress () const |
| Queries whether the socket is currently configured to allow address reuse. | |
| void | setReceiveBufferSize (std::size_t size) |
| Sets the socket's receive buffer size (SO_RCVBUF). | |
| int | getReceiveBufferSize () const |
| Retrieves the current receive buffer size (SO_RCVBUF) of the socket. | |
| void | setSendBufferSize (std::size_t size) |
| Sets the socket's send buffer size (SO_SNDBUF). | |
| int | getSendBufferSize () const |
| Retrieves the current send buffer size (SO_SNDBUF) of the socket. | |
| void | setSoLinger (bool enable, int seconds) |
| Configures the socket's linger behavior (SO_LINGER) during close. | |
| std::pair< bool, int > | getSoLinger () const |
| Retrieves the current SO_LINGER configuration of the socket. | |
| void | setKeepAlive (bool on) |
| Enables or disables TCP-level keepalive behavior on the socket (SO_KEEPALIVE). | |
| bool | getKeepAlive () const |
| Checks whether TCP-level keepalive (SO_KEEPALIVE) is currently enabled. | |
| void | setSoRecvTimeout (int millis) |
| Sets the socket receive timeout (SO_RCVTIMEO) in milliseconds. | |
| void | setSoSendTimeout (int millis) |
| Sets the socket send timeout (SO_SNDTIMEO) in milliseconds. | |
| int | getSoRecvTimeout () const |
| Retrieves the socket receive timeout (SO_RCVTIMEO) in milliseconds. | |
| int | getSoSendTimeout () const |
| Retrieves the socket send timeout (SO_SNDTIMEO) in milliseconds. | |
| void | setNonBlocking (bool nonBlocking) |
| Enables or disables non-blocking mode on the socket. | |
| bool | getNonBlocking () const |
| Queries whether the socket is currently in non-blocking mode. | |
| void | setTcpNoDelay (bool on) |
| Enables or disables Nagle’s algorithm (TCP_NODELAY) on TCP sockets. | |
| bool | getTcpNoDelay () const |
| Queries whether Nagle's algorithm (TCP_NODELAY) is currently disabled. | |
| void | setBroadcast (bool on) |
| Enables or disables the ability to send UDP broadcast messages. | |
| bool | getBroadcast () const |
| Checks whether the socket is currently allowed to send broadcast messages. | |
| void | setIPv6Only (bool enable) |
| Enables or disables IPV6_V6ONLY mode for IPv6-capable sockets. | |
| bool | getIPv6Only () const |
| Queries whether the IPV6_V6ONLY option is enabled on this socket. | |
| void | setReusePort (const bool enable) |
| Enables or disables the SO_REUSEPORT socket option. | |
| bool | getReusePort () const |
| Checks whether the SO_REUSEPORT option is currently enabled on the socket. | |
| void | setMulticastTTL (int ttl) |
| Set the default multicast hop limit / TTL for this socket. | |
| int | getMulticastTTL () const |
| Get the socket’s default multicast hop limit / TTL. | |
| void | setMulticastLoopback (bool enable) |
| Enable or disable multicast loopback for this socket. | |
| bool | getMulticastLoopback () const |
| Read the socket’s multicast loopback flag. | |
| void | setMulticastInterfaceIPv4 (in_addr addr) |
| Select the outgoing IPv4 interface for multicast. | |
| void | setMulticastInterfaceIPv6 (unsigned int ifindex) |
| Select the outgoing IPv6 interface for multicast. | |
| void | joinGroupIPv4 (in_addr group, in_addr iface) |
| Join an IPv4 any-source multicast (ASM) group on a specific interface. | |
| void | leaveGroupIPv4 (in_addr group, in_addr iface) |
| Leave a previously joined IPv4 multicast group on a specific interface. | |
| void | joinGroupIPv6 (in6_addr group, unsigned int ifindex) |
| Join an IPv6 any-source multicast (ASM) group on a specific interface index. | |
| void | leaveGroupIPv6 (in6_addr group, unsigned int ifindex) |
| Leave a previously joined IPv6 multicast group on a specific interface index. | |
Static Protected Member Functions | |
| static in_addr | resolveIPv4 (std::string_view host) |
| Resolve a host string to an IPv4 address (in_addr, network byte order). | |
| static in6_addr | resolveIPv6 (std::string_view host) |
| Resolve a host string to an IPv6 address (in6_addr). | |
| static unsigned int | toIfIndexFromString (const std::string &iface) |
| Convert a human-friendly interface identifier to an IPv6 interface index. | |
| Static Protected Member Functions inherited from jsocketpp::DatagramSocket | |
| static void | throwSizeMismatch (const std::size_t expected, const std::size_t actual, const bool isProbedKnown) |
| Throw a descriptive exception when a UDP datagram’s size differs from what was expected. | |
| static std::span< const std::byte > | asBytes (const std::string_view sv) noexcept |
| View a textual buffer as raw bytes without copying. | |
| template<typename T> | |
| static std::array< std::byte, sizeof(T)> | encodeLengthPrefixBE (std::size_t n) |
| Encode a length value into a fixed-size, big-endian (network-order) byte array. | |
| Static Protected Member Functions inherited from jsocketpp::SocketOptions | |
| static bool | is_ipv4_multicast (const in_addr v4) |
| Test whether an IPv4 address is in the multicast range (224.0.0.0/4). | |
| static bool | is_ipv6_multicast (const in6_addr &v6) |
| Test whether an IPv6 address is in the multicast range (ff00::/8). | |
| static int | detectFamily (SOCKET fd) |
| Determine the address family (AF_INET or AF_INET6) of a socket. | |
Private Attributes | |
| std::string | _currentGroup {} |
| Last joined multicast group address. | |
| std::string | _currentInterface {} |
| Interface used for multicast. | |
| int | _ttl = 1 |
| Default TTL (Time To Live) value for multicast packets. | |
| bool | _loopbackEnabled = true |
| Controls whether multicast packets loop back to the sending host. | |
Additional Inherited Members | |
| Protected Member Functions inherited from jsocketpp::DatagramSocket | |
| std::size_t | readIntoBuffer (char *buf, std::size_t len, DatagramReceiveMode mode, int recvFlags, sockaddr_storage *outSrc, socklen_t *outSrcLen, std::size_t *outDatagramSz, bool *outTruncated) const |
| Low-level, single-recv primitive that copies one UDP datagram into a caller buffer. | |
| void | cleanup () |
| Internal helper that releases socket resources and resets all internal state. | |
| void | cleanupAndThrow (int errorCode) |
| Releases all socket resources and throws a SocketException with the given error code. | |
| void | cleanupAndRethrow () |
| Cleans up the datagram socket and rethrows the currently active exception. | |
| std::size_t | chooseReceiveSize () const |
| Decide how many bytes to attempt to receive for the next UDP datagram. | |
| void | rememberRemote (const sockaddr_storage &src, const socklen_t len) const noexcept |
| Remember the last remote peer after an unconnected receive. | |
| void | enforceSendCapConnected (const std::size_t payloadSize) const |
| Enforce UDP payload size limits for connected datagram sends. | |
| void | sendUnconnectedTo (std::string_view host, Port port, const void *data, std::size_t len) |
| Resolve and send one unconnected UDP datagram to the first compatible destination. | |
| template<typename T> | |
| void | sendPrefixedConnected (const std::span< const std::byte > payload) const |
| Build and send a length-prefixed UDP datagram to the connected peer (no pre-wait). | |
| template<typename T> | |
| void | sendPrefixedUnconnected (const std::string_view host, const Port port, const std::span< const std::byte > payload) |
| Build and send a length-prefixed UDP datagram to (host, port) on the unconnected path. | |
| void | cacheLocalEndpoint () noexcept |
| Cache the actual local endpoint assigned by the OS. | |
| bool | tryGetRemoteSockaddr (sockaddr_storage &out, socklen_t &outLen) const |
| Retrieve the remote endpoint sockaddr for this socket, if available. | |
| Protected Member Functions inherited from jsocketpp::SocketOptions | |
| void | setSocketFd (const SOCKET sock) noexcept |
| Updates the socket descriptor used by this object. | |
| virtual bool | isPassiveSocket () const noexcept |
| Indicates whether the socket behaves as a passive (listening) socket. | |
Cross-platform multicast UDP socket class (IPv4/IPv6).
The MulticastSocket class extends DatagramSocket to provide high-level, Java-inspired support for multicast networking. It works on both Windows and Linux, and supports both IPv4 and IPv6 multicast groups.
| std::string MulticastSocket::getCurrentGroup | ( | ) | const |
Returns the last multicast group joined (for reference/debug).
|
staticprotected |
Convert a human-friendly interface identifier to an IPv6 interface index.
Interprets iface and returns a numeric interface index suitable for APIs that require an IPv6 egress/interface selector (e.g., IPV6_MULTICAST_IF, IPv6 multicast join/leave).
Accepted forms:
This helper performs no socket I/O; it only converts/looks up the identifier.
| [in] | iface | Interface selector as described above. Pass "" to request the default (index 0). |
iface. Returns 0 for the empty string.| SocketException |
|
|
private |
Last joined multicast group address.
|
private |
Interface used for multicast.
|
private |
Controls whether multicast packets loop back to the sending host.
Default is true, which means:
|
private |
Default TTL (Time To Live) value for multicast packets.
Default value is 1, which means:
This conservative default prevents accidental network flooding and provides a safe starting point for most applications.