boost::asio::ip::multicast::join_group does not work

boost::asio::ip::multicast::join_group does not work

本文关键字:group does work not join asio ip multicast boost      更新时间:2023-10-16

我尝试了这个例子,但它不起作用。显然,它没有设置IPPROTO_IP/IP_MULTICAST_IF选项。我只能找到boost::asio::ip::multicast::outbound_interface的IPPROTO_IP/IP_MULTICAST_IF,我尝试了,但失败了。是否有任何方法使boost::asio::ip::多播工作而不调用c级setsockopt?

boost::asio::ip::udp::endpoint listen_endpoint(
    listen_address, multicast_port);
socket_.open(listen_endpoint.protocol());
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket_.bind(listen_endpoint);
// Join the multicast group.
socket_.set_option(
    boost::asio::ip::multicast::join_group(multicast_address));

正确答案:

boost::asio::ip::udp::endpoint listen_endpoint(udp::v4(), multicast_port); 
...
socket_.set_option(multicast::join_group(
  address::from_string(multicast_address).to_v4(), 
  address::from_string(interface).to_v4()));

我认为在udp组播的boost示例代码中存在错误。

在示例代码中,它们将套接字绑定到本地接口,但对于udp多播,您必须绑定到udp多播组的IP和端口。

socket_.bind(listen_endpoint);
应:

socket_.bind(
    boost::asio::ip::udp::endpoint( multicast_address, multicast_port ) );

参见multicast howto:

…对于接收多播数据报的进程,它必须请求内核要加入组并绑定正在发送的数据报的端口出现。UDP层同时使用目的地址和端口to将数据包拆分并决定哪个套接字将它们发送到…

…有必要通知内核我们是哪个多播组感兴趣的。也就是说,我们必须要求内核"连接"它们组播组…

检查您是否在正确的接口与netstat -g | grep <multicast_group_ip>加入组

这是我认为错误的boost示例代码:

boost::asio::ip::udp::endpoint listen_endpoint(
    listen_address, multicast_port);
socket_.open(listen_endpoint.protocol());
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket_.bind(listen_endpoint);
// Join the multicast group.
socket_.set_option(
    boost::asio::ip::multicast::join_group(multicast_address));
socket_.async_receive_from(
    boost::asio::buffer(data_, max_length), sender_endpoint_,
    boost::bind(&receiver::handle_receive_from, this,
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));