我在这里遵循 Boost 的 UDP 时间服务器教程. 我用这些修改预定义值的代码:
short multicast_port = 13; // (in class receiver)
和 main((:
//if (argc != 3) and the code for argv that follows are commented out
receiver r(io_context, boost::asio::ip::make_address("127.0.0.1"), boost::asio::ip::make_address("127.0.0.1")); //
引发此错误:
set_option: The requested address is not valid in its context
我尝试了"0.0.0.0"和"127.0.0.1"和其他值。仍然得到相同的错误。有人可以帮我弄清楚出了什么问题吗?
为了澄清事情,这是我使用的代码:
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <array>
#include <string>
using boost::asio::ip::udp;
using std::cout;
using std::cin;
using std::endl;
class receiver
{
private:
boost::asio::ip::udp::socket socket_;
boost::asio::ip::udp::endpoint sender_endpoint_;
std::array<char, 1024> data_;
short multicast_port = 13000;
public:
receiver(boost::asio::io_context& io_context,
const boost::asio::ip::address& listen_address,
const boost::asio::ip::address& multicast_address)
: socket_(io_context)
{
// Create the socket so that multiple may be bound to the same address.
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));
do_receive();
}
private:
void do_receive()
{
socket_.async_receive_from(
boost::asio::buffer(data_), sender_endpoint_,
[this](boost::system::error_code ec, std::size_t length)
{
if (!ec)
{
std::cout.write(data_.data(), length);
std::cout << std::endl;
do_receive();
}
});
}
};
int main(int argc, char* argv[])
{
try
{
boost::asio::io_context io_context;
receiver r(io_context, boost::asio::ip::make_address("127.0.0.1"), boost::asio::ip::make_address("127.0.0.1"));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "n";
}
return 0;
}
构造函数的第三个参数是多播组地址。
127.0.0.1 不是多播组地址,0.0.0.0 也不是。
请参阅您的来源。
也许很久以前无法回答,但我遇到了同样的问题,也许其他人也面临同样的问题。所以这可能不是最好的解决方案,但至少是让它工作的方法。
基本上,您使用以太网适配器IP加入组播组,这似乎比在正在收听的端口上打开所有以太网适配器更自然。请小心使用有效的 IP,因为如果没有,boost 会引发异常。到目前为止,我发现的唯一解决方案是在接收器方法调用周围使用 try/catch 。
当您尝试加入多播组时,似乎需要其中一个以太网适配器的 IP 地址。我建议编辑它并使用静态 IP 地址(系统>网络>以太网连接(。
至于代码,只需要将这一行更改为:
// Join the multicast group.
socket_.set_option(
boost::asio::ip::multicast::join_group(multicast_address.to_v4(), listen_address.to_v4()));
我不确定是否需要 .to_v4((,但它没有伤害。