5 // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
14 #include <boost/asio.hpp>
16 constexpr short multicast_port
= 30001;
21 receiver(boost::asio::io_context
& io_context
,
22 const boost::asio::ip::address
& listen_address
,
23 const boost::asio::ip::address
& multicast_address
)
26 // Create the socket so that multiple may be bound to the same address.
27 boost::asio::ip::udp::endpoint
listen_endpoint(
28 listen_address
, multicast_port
);
29 socket_
.open(listen_endpoint
.protocol());
30 socket_
.set_option(boost::asio::ip::udp::socket::reuse_address(true));
31 socket_
.bind(listen_endpoint
);
33 // Join the multicast group.
35 boost::asio::ip::multicast::join_group(multicast_address
));
43 socket_
.async_receive_from(
44 boost::asio::buffer(data_
), sender_endpoint_
,
45 [this](boost::system::error_code ec
, std::size_t length
)
49 std::cout
.write(data_
.data(), length
);
50 std::cout
<< std::endl
;
57 boost::asio::ip::udp::socket socket_
;
58 boost::asio::ip::udp::endpoint sender_endpoint_
;
59 std::array
<char, 1024> data_
;
62 int main(int argc
, char* argv
[])
68 std::cerr
<< "Usage: receiver <listen_address> <multicast_address>\n";
69 std::cerr
<< " For IPv4, try:\n";
70 std::cerr
<< " receiver 0.0.0.0 239.255.0.1\n";
71 std::cerr
<< " For IPv6, try:\n";
72 std::cerr
<< " receiver 0::0 ff31::8000:1234\n";
76 boost::asio::io_context io_context
;
77 receiver
r(io_context
,
78 boost::asio::ip::make_address(argv
[1]),
79 boost::asio::ip::make_address(argv
[2]));
82 catch (std::exception
& e
)
84 std::cerr
<< "Exception: " << e
.what() << "\n";