A collection of obvious ideas.


Ugh: How to specify network interface for boost::asio::ip::udp multicast receive

With some funky formatting so it’ll fit better….

I have the socket_ as a private variable in a class, that’s why scoped_ptr is used.

I use the Sigar API for a cross platform way to get a list of interface addresses. You’ll see people trying to use boost, but that does not give a list of interface addresses. It uses hostname resolution, which only works if you have a DNS or something to look up the hostname.

boost::scoped_ptr<boost::asio::ip::udp::socket> socket_;

#ifdef _linux
// for linux, use the multicast address as the bind

boost::asio::ip::udp::endpoint listen_endpoint(
   multicast_address,
   multicast_port
);

#else
// for windows, use the interface address

boost::asio::ip::udp::endpoint listen_endpoint(
   interface_address,
   multicast_port
);

#endif

socket_.reset(
    new boost::asio::ip::udp::socket(
        io_service,
        listen_endpoint.protocol()
   )
);

socket_->bind(listen_endpoint);

if( interface_address.is_v4() ){
    socket_->set_option(
        boost::asio::ip::multicast::join_group(
            multicast_address.to_v4(),
            interface_address.to_v4()
        )
    );

}else{

    // need to find cross platform way to get interface number

    socket_->set_option(
       boost::asio::ip::multicast::join_group(
           multicast_address.to_v6(),
           <ipv6 interface index int here>
        )
   );
}

Binding to “0.0.0.0” only seems to listen on one interface.

posted : Friday, November 30th, 2012

tags :

Comments (View)