This is a simple example on how to do UDP multicast sending and receiving.
#include <array>
#include <iostream>
const char multicast_group[] = "239.255.0.1";
const unsigned short multicast_port = 47777;
const char send_msg[] = "Welcome to our multicast group!";
const int send_len = sizeof(send_msg) - 1;
int main()
{
try {
recv_socket.
bind(multicast_port);
static_cast<void>(sent);
std::array<char, 256> buffer{};
std::string source;
unsigned short source_port = 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(), res.
bytes);
std::cout << std::endl;
return 0;
}
{
std::cerr << e.
what() << std::endl;
return 1;
}
}
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.
IOResult timedReceiveFrom(void *buffer, size_t len, std::string &sourceAddress, unsigned short &sourcePort, int timeout)
IOResult sendTo(const void *buffer, size_t len, std::string_view foreignAddress, unsigned short foreignPort)
void setMulticastTTL(unsigned char multicastTTL)
void leaveGroup(const std::string &multicastGroup)
void joinGroup(const std::string &multicastGroup)