5 // Copyright (c) 2003-2012 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)
13 #include <boost/asio.hpp>
14 #include "boost/bind.hpp"
16 const short multicast_port = 30001;
21 receiver(boost::asio::io_service& io_service,
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));
37 socket_.async_receive_from(
38 boost::asio::buffer(data_, max_length), sender_endpoint_,
39 boost::bind(&receiver::handle_receive_from, this,
40 boost::asio::placeholders::error,
41 boost::asio::placeholders::bytes_transferred));
44 void handle_receive_from(const boost::system::error_code& error,
49 std::cout.write(data_, bytes_recvd);
50 std::cout << std::endl;
52 socket_.async_receive_from(
53 boost::asio::buffer(data_, max_length), sender_endpoint_,
54 boost::bind(&receiver::handle_receive_from, this,
55 boost::asio::placeholders::error,
56 boost::asio::placeholders::bytes_transferred));
61 boost::asio::ip::udp::socket socket_;
62 boost::asio::ip::udp::endpoint sender_endpoint_;
63 enum { max_length = 1024 };
64 char data_[max_length];
67 int main(int argc, char* argv[])
73 std::cerr << "Usage: receiver <listen_address> <multicast_address>\n";
74 std::cerr << " For IPv4, try:\n";
75 std::cerr << " receiver 0.0.0.0 239.255.0.1\n";
76 std::cerr << " For IPv6, try:\n";
77 std::cerr << " receiver 0::0 ff31::8000:1234\n";
81 boost::asio::io_service io_service;
82 receiver r(io_service,
83 boost::asio::ip::address::from_string(argv[1]),
84 boost::asio::ip::address::from_string(argv[2]));
87 catch (std::exception& e)
89 std::cerr << "Exception: " << e.what() << "\n";