【发布时间】:2018-03-03 22:17:51
【问题描述】:
我正在关注 Boost 的 UDP 时间服务器教程here .我用这些修改代码以获得预定义的值:
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;
}
【问题讨论】:
-
1024以下的端口号有特权,你需要是某种“管理员”或“超级用户”才能使用1024以下的端口。
-
此外,您显示的小代码不会调用
set_option或执行任何特定于多播的操作。 Minimal, Complete, and Verifiable Example 将大大有助于我们为您提供帮助。 -
我将端口更改为 13000,但仍然出错。我只是按照链接中的示例代码。我假设它已经过测试,因为它是作为官方文档发布的。
-
停止转发此问题。
标签: c++ boost udp multicast receiver