Skip to content

Instantly share code, notes, and snippets.

@elvinio
Last active August 29, 2015 14:26
Show Gist options
  • Save elvinio/c94c52cb43fe1579afdf to your computer and use it in GitHub Desktop.
Save elvinio/c94c52cb43fe1579afdf to your computer and use it in GitHub Desktop.
Example program on how to use Boost ASIO to subscribe to a multicast server.
#include <boost/asio.hpp>
#include <boost/exception/diagnostic_information.hpp>
#define BUFFERSIZE 2048
using boost::asio::ip::udp;
int main(){
boost::asio::io_service* io_service = nullptr;
boost::asio::ip::udp::socket* socket = nullptr;
int32_t port = 12911;
std::string ip = "237.0.0.11";
socket->open(boost::asio::ip::udp::v4());
socket->set_option(udp::socket::reuse_address(true));
socket->bind(udp::endpoint(boost::asio::ip::address_v4::any(), port));
boost::asio::ip::address address = boost::asio::ip::address::from_string(ip);
socket->set_option(boost::asio::ip::multicast::join_group(address));
char buffer[BUFFERSIZE];
udp::endpoint senderEndpoint;
while (true){
try{
bytesRead = socket->receive_from(boost::asio::buffer(buffer, BUFFERSIZE), senderEndpoint);
}
catch(const boost::exception &e)
{
std::cerr << "Error. Reason: " << boost::diagnostic_information(e) << '\n';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment