增强UDP多播接收器:set_option:请求的地址在其上下文中无效

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了增强UDP多播接收器:set_option:请求的地址在其上下文中无效相关的知识,希望对你有一定的参考价值。

我正在关注Boost的UDP Time服务器教程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() << "
";
    }


    return 0;
}    

以上是关于增强UDP多播接收器:set_option:请求的地址在其上下文中无效的主要内容,如果未能解决你的问题,请参考以下文章

udp广播,单播,多播

绑定多播 (UDP) 套接字是啥意思?

未使用 PYQT5 多播 UDP 接收数据报

如何接收组播 UDP?

NodeJS 数据报 - 接收 IPv6 多播

Windows Phone 8 上的 UDP 多播组