This is a simple example on how to do UDP multicast.
#include <simple_socket/UDPSocket.h>
#include <array>
#include <iostream>
static const char multicast_group[] = "239.255.0.1";
static const unsigned short multicast_port = 47777;
static const char send_msg[] = "Welcome to our multicast group!";
static const int send_len = sizeof(send_msg) - 1;
int main()
{
try {
recv_socket.
bind(multicast_port);
send_socket.
sendTo(send_msg, send_len, multicast_group, multicast_port);
std::array<char, 256> buffer{};
std::string source;
unsigned short source_port = 0;
int received = recv_socket.
timedReceiveFrom(buffer.data(), buffer.size(), source, source_port, 1000);
if (received == 0)
{
std::cerr << "Timed out waiting for multicast datagram." << std::endl;
return 1;
}
std::cout << "Received from " << source << ":" << source_port << ": ";
std::cout.write(buffer.data(), received);
std::cout << std::endl;
}
{
std::cerr << e.
what() << std::endl;
return 1;
}
return 0;
}
void bind(unsigned short localPort=0)
void setReuseAddress(bool enable)
Enable or disable local address reuse.
Signals a problem with the execution of a socket call.
const char * what() const noexcept
Returns a C-string describing the cause of the current error.
int timedReceiveFrom(void *buffer, size_t len, std::string &sourceAddress, unsigned short &sourcePort, int timeout)
void setMulticastTTL(unsigned char multicastTTL)
void joinGroup(const std::string &multicastGroup)
void sendTo(const void *buffer, size_t len, std::string_view foreignAddress, unsigned short foreignPort)
void leaveGroup(const std::string &multicastGroup)