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

Cross-platform multicast UDP socket class (IPv4/IPv6). More...

#include <MulticastSocket.hpp>

Inheritance diagram for jsocketpp::MulticastSocket:
Collaboration diagram for jsocketpp::MulticastSocket:

Public Member Functions

 MulticastSocket (Port port=0, std::size_t bufferSize=2048)
 Constructs a multicast socket optionally bound to a local port and buffer size.
void joinGroup (const std::string &groupAddr, const std::string &iface="")
 Joins a multicast group.
void leaveGroup (const std::string &groupAddr, const std::string &iface="")
 Leaves a multicast group.
void setMulticastInterface (const std::string &iface)
 Sets the default interface for outgoing multicast packets.
std::string getMulticastInterface () const
 Gets the currently set interface for outgoing multicast packets.
void setTimeToLive (int ttl)
 Set the time-to-live (TTL) for outgoing multicast packets.
int getTimeToLive () const
 Get the current time-to-live (TTL) value for outgoing multicast packets.
void setLoopbackMode (bool enable)
 Enables or disables multicast loopback.
int getLoopbackMode () const
 Get the current multicast loopback mode setting.
std::string getCurrentGroup () const
 Returns the last multicast group joined (for reference/debug).
Public Member Functions inherited from jsocketpp::DatagramSocket
 DatagramSocket (Port port, std::size_t bufferSize=2048)
 Constructs a UDP socket optionally bound to a local port.
 DatagramSocket (std::string_view host, Port port, std::size_t bufferSize=2048)
 Construct a datagram socket to a remote host and port.
 ~DatagramSocket () noexcept
 Destructor. Closes the socket and frees resources.
 DatagramSocket (const DatagramSocket &)=delete
 Copy constructor (deleted).
DatagramSocketoperator= (const DatagramSocket &)=delete
 Copy assignment operator (deleted).
 DatagramSocket (DatagramSocket &&other) noexcept
 Move constructor.
DatagramSocketoperator= (DatagramSocket &&other) noexcept
 Move assignment operator.
void bind () const
 Bind the datagram socket to the configured port set in the constructor.
void connect (int timeoutMillis=-1)
 Connects the datagram socket to the remote host and port with optional timeout handling.
size_t write (const DatagramPacket &packet) const
 Write data to a remote host using a DatagramPacket.
size_t write (std::string_view message) const
 Write data to the socket (connected UDP) from a string_view.
size_t write (std::string_view message, std::string_view host, Port port) const
 Send a datagram to a specific host and port (connectionless UDP).
size_t read (DatagramPacket &packet, bool resizeBuffer=true) const
 Receives a UDP datagram and fills the provided DatagramPacket.
template<typename T>
read ()
 Read a trivially copyable type from the socket (connected UDP).
template<typename T>
recvFrom (std::string *senderAddr, Port *senderPort)
 Receive a datagram into a trivially copyable type.
void close ()
 Close the datagram socket.
void setNonBlocking (bool nonBlocking) const
 Set the socket to non-blocking or blocking mode.
void setTimeout (int millis) const
 Sets the socket's receive timeout.
void setOption (int level, int optName, int value) const
 Set a socket option (integer value).
int getOption (int level, int optName) const
 Get a socket option (integer value).
std::string getLocalSocketAddress () const
 Get the local socket's address as a string (ip:port).
bool isValid () const
 Check if the datagram socket is valid (open).
bool isConnected () const
 Check if the datagram socket is connected to a remote host.
void enableBroadcast (bool enable) const
 Enable or disable the ability to send broadcast packets.

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
void cleanupAndThrow (int errorCode)
 Cleans up datagram socket resources and throws a SocketException.
Protected Attributes inherited from jsocketpp::DatagramSocket
SOCKET _sockFd = INVALID_SOCKET
 Underlying socket file descriptor.
addrinfo * _addrInfoPtr = nullptr
 Address info pointer for bind/connect.
addrinfo * _selectedAddrInfo = nullptr
 Selected address info for connection.

Detailed Description

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.

What is Multicast?

  • Multicast allows you to send a single UDP packet to multiple hosts subscribed to a multicast group address.
  • It is useful for applications such as real-time data feeds, streaming media, and network discovery protocols.
  • Each group is identified by a special IP address (224.0.0.0–239.255.255.255 for IPv4, ff00::/8 for IPv6).

Usage Example (Receiving)

using namespace jsocketpp;
* // Create a multicast socket bound to port 5000
MulticastSocket socket(5000);
* // Join the multicast group "239.255.0.1" on the default interface
socket.joinGroup("239.255.0.1");
* // Receive a datagram packet (blocking)
DatagramPacket packet(1500); // 1500-byte buffer
size_t n = socket.read(packet);
std::string data(packet.buffer.begin(), packet.buffer.begin() + n);
std::cout << "Received: " << data << " from " << packet.address << ":" << packet.port << std::endl;
// Leave the group when done
socket.leaveGroup("239.255.0.1");
Represents a UDP datagram packet, encapsulating both payload and addressing information.
Definition DatagramPacket.hpp:48
MulticastSocket(Port port=0, std::size_t bufferSize=2048)
Constructs a multicast socket optionally bound to a local port and buffer size.
Definition MulticastSocket.cpp:5
A C++ socket library providing Java-style networking interfaces.
Definition BufferView.hpp:13

Usage Example (Sending)

using namespace jsocketpp;
socket.setTimeToLive(2); // Limit to 2 router hops
DatagramPacket packet("Hello, multicast!", "239.255.0.1", 5000);
socket.write(packet);
size_t write(const DatagramPacket &packet) const
Write data to a remote host using a DatagramPacket.
Definition DatagramSocket.cpp:232
void setTimeToLive(int ttl)
Set the time-to-live (TTL) for outgoing multicast packets.
Definition MulticastSocket.cpp:393

Features

  • Join/leave multicast groups on a specific interface or all interfaces.
  • Works with both IPv4 and IPv6 multicast groups.
  • Set multicast TTL (time-to-live/hop limit).
  • Set outgoing interface for multicast packets.
  • Control whether multicast packets sent by this socket are received by itself (loopback).
  • Modern, Java-style, exception-safe C++ API.
See also
jsocketpp::DatagramSocket
jsocketpp::DatagramPacket

Constructor & Destructor Documentation

◆ MulticastSocket()

MulticastSocket::MulticastSocket ( Port port = 0,
std::size_t bufferSize = 2048 )
explicit

Constructs a multicast socket optionally bound to a local port and buffer size.

Parameters
portThe local UDP port to bind to (0 means any port). On a server, you typically want to specify a fixed port that clients can connect to. On clients, using port 0 lets the system assign any available port.
bufferSizeThe size of the receive buffer (default: 2048 bytes). Larger values may be needed for high-volume data reception.
Exceptions
SocketExceptionon failure.

Member Function Documentation

◆ getCurrentGroup()

std::string MulticastSocket::getCurrentGroup ( ) const

Returns the last multicast group joined (for reference/debug).

Returns
String containing the IP address of the last joined multicast group.

◆ getLoopbackMode()

int jsocketpp::MulticastSocket::getLoopbackMode ( ) const
inline

Get the current multicast loopback mode setting.

Returns whether the socket is configured to receive its own multicast packets:

  • true: The socket will receive its own multicast packets (loopback enabled)
  • false: The socket will not receive its own multicast packets (loopback disabled)
Returns
true if loopback is enabled, false if disabled.

◆ getMulticastInterface()

std::string jsocketpp::MulticastSocket::getMulticastInterface ( ) const
inline

Gets the currently set interface for outgoing multicast packets.

Returns the interface that was set using setMulticastInterface():

  • For IPv4: the IP address of the interface (e.g., "192.168.1.5")
  • For IPv6: the interface name (e.g., "eth0") or index
  • Empty string if no specific interface is set
Returns
The current multicast interface address/name or empty string.

◆ getTimeToLive()

int jsocketpp::MulticastSocket::getTimeToLive ( ) const
inline

Get the current time-to-live (TTL) value for outgoing multicast packets.

Returns the TTL value that determines how many network hops multicast packets can traverse:

  • 0: Restricted to the same host
  • 1: Restricted to the same subnet
  • 32: Restricted to the same site
  • 64: Restricted to the same region
  • 128: Restricted to the same continent
  • 255: Unrestricted
Returns
The current TTL value (0-255).

◆ joinGroup()

void MulticastSocket::joinGroup ( const std::string & groupAddr,
const std::string & iface = "" )

Joins a multicast group.

Parameters
groupAddrMulticast group address (e.g., "239.255.0.1" or "ff02::1"). IPv4 multicast addresses range from 224.0.0.0 to 239.255.255.255. IPv6 multicast addresses start with 'ff'.
ifaceOptional: name or IP of local interface to join on (default: any). Useful when the host has multiple network interfaces and you want to receive multicast only on a specific one.
Exceptions
SocketExceptionon failure.

◆ leaveGroup()

void MulticastSocket::leaveGroup ( const std::string & groupAddr,
const std::string & iface = "" )

Leaves a multicast group.

Parameters
groupAddrMulticast group address to leave (e.g., "239.255.0.1" or "ff02::1").
ifaceOptional: name or IP of local interface to leave on (default: any). Must match the interface specified in joinGroup() if one was used.
Exceptions
SocketExceptionon failure.

◆ setLoopbackMode()

void MulticastSocket::setLoopbackMode ( bool enable)

Enables or disables multicast loopback.

Parameters
enableTrue to enable (receive own multicast packets), false to disable (don't receive own packets). Enable for testing or when the local host needs to process the same multicast packets as other receivers.
Exceptions
SocketExceptionon failure.

◆ setMulticastInterface()

void MulticastSocket::setMulticastInterface ( const std::string & iface)

Sets the default interface for outgoing multicast packets.

For IPv4, the interface is specified as an IP address (e.g., "192.168.1.5"). For IPv6, the interface is specified as an interface name (e.g., "eth0") or numeric index (e.g., "2").

Parameters
ifaceThe interface address (IPv4) or name/index (IPv6). An empty string disables interface selection.
Exceptions
SocketExceptionif setting the option fails or input is invalid.

◆ setTimeToLive()

void MulticastSocket::setTimeToLive ( int ttl)

Set the time-to-live (TTL) for outgoing multicast packets.

For IPv4, this sets the IP_MULTICAST_TTL socket option. For IPv6, this sets the IPV6_MULTICAST_HOPS socket option.

Parameters
ttlNumber of network hops allowed (0-255):
  • 0: Restricted to the same host
  • 1: Restricted to the same subnet (default)
  • 32: Restricted to the same site
  • 64: Restricted to the same region
  • 128: Restricted to the same continent
  • 255: Unrestricted
Exceptions
SocketExceptionon failure.

Member Data Documentation

◆ _currentGroup

std::string jsocketpp::MulticastSocket::_currentGroup {}
private

Last joined multicast group address.

◆ _currentInterface

std::string jsocketpp::MulticastSocket::_currentInterface {}
private

Interface used for multicast.

◆ _loopbackEnabled

bool jsocketpp::MulticastSocket::_loopbackEnabled = true
private

Controls whether multicast packets loop back to the sending host.

Default is true, which means:

  • The sending host can receive its own multicast packets
  • Useful for testing and debugging
  • Allows applications on the same host to communicate
  • May be disabled for production if self-reception is not needed

◆ _ttl

int jsocketpp::MulticastSocket::_ttl = 1
private

Default TTL (Time To Live) value for multicast packets.

Default value is 1, which means:

  • Packets will only be delivered within the local subnet
  • Packets will not cross any routers
  • Ideal for local network discovery and communication

This conservative default prevents accidental network flooding and provides a safe starting point for most applications.


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