我是多播编程的初学者。我正在使用boost::asio
来编写一些多播数据。
我用代码
编写了一个程序boost::array<char,1500> _receiveBuf;
void WaitForNextRead()
{
_receiveSocket->async_receive_from(
boost::asio::buffer(_receiveBuf, 1500),
_receiveEndPoint,
boost::bind(
&AsyncReadHandler,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void AsyncReadHandler(
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes received.
)
{
std::cout << _receiveEndPoint.address() << ":" << _receiveEndPoint.port() << ":" << std::string(_receiveBuf.c_array(), bytes_transferred) << "\n";
WaitForNextRead();
}
int main()
{
std::string address;
int port;
std::cin >> address;
std::cin >> port;
boost::asio::io_service ioService;
_receiveSocket = new udp::socket( ioService );
_receiveSocket->open( udp::v4() );
_receiveSocket->set_option( udp::socket::reuse_address(true) );
_receiveSocket->bind( udp::endpoint( address::from_string("0.0.0.0"), port ) );
_receiveSocket->set_option( multicast::join_group( address::from_string(address) ) );
_receiveEndPoint.address(address::from_string(address));
_receiveEndPoint.port(port);
WaitForNextRead();
ioService.run();
return 0;
}
我的实例A正在加入:239.1.1.1:12345 我的实例B正在加入:239.1.127.1:12345
非常奇怪的是,实例A和B都将从两个地址获取消息!!
我是否错过了一些套接字选项?
PS: 这是我的路由表
Destination Gateway Genmask Flags Metric Ref Use Iface
224.0.0.0 * 240.0.0.0 U 0 0 0 eth1
答案 0 :(得分:1)
我想我找到了答案。
参见:
http://man7.org/linux/man-pages/man7/ip.7.html
https://bugzilla.redhat.com/show_bug.cgi?id=231899
Linux有一个错误,即广播IP_ADD_MEMBERSHIP是对所有套接字的全局操作,即使是另一个进程的一部分。我们需要将选项IP_MULTICAST_ALL设置为零(0)以解决此问题。