boost::asio UDP 广播

2021-12-24 00:00:00 udp broadcast c++ boost boost-asio

我想使用 boost::asio 向本地网络中的所有计算机广播 UDP 消息.通过我想出的例子

I want to broadcast UDP messages to all computers in a local network using boost::asio. Working through the examples I came up with

try {
    socket.open(boost::asio::ip::udp::v4());
    boost::asio::socket_base::broadcast option(true);
    socket.set_option(option);
    endpoint = boost::asio::ip::udp::endpoint(
        boost::asio::ip::address::from_string("192.168.1.255"),
        port);
}
catch(std::exception &e) {
}

并且想要从我的队列中广播消息

and want to broadcast messages from my queue with

while(!queue.empty()) {
    std::string message = queue.front();
    boost::system::error_code ignored_error;
    socket.send_to(
        boost::asio::buffer(message),
        endpoint,
        0, ignored_error);
    queue.pop_front();
}

但我的代码在第一个代码块中抛出异常 invalid argument 异常.不过,它对 127.0.0.1 工作正常.我做错了什么?

but my code throws an exception invalid argument exception in the first code block. It works fine for 127.0.0.1 though. What am I doing wrong?

推荐答案

尝试使用以下代码片段发送 UDP 广播,利用 ba::ip::address_v4::broadcast() 调用获取端点:

Try the following code snippet to send a UDP broadcast, utilizing the ba::ip::address_v4::broadcast() call to get an endpoint:

    bs::error_code error;
    ba::ip::udp::socket socket(_impl->_ioService);

    socket.open(ba::ip::udp::v4(), error);
    if (!error)
    {
        socket.set_option(ba::ip::udp::socket::reuse_address(true));
        socket.set_option(ba::socket_base::broadcast(true));

        ba::ip::udp::endpoint senderEndpoint(ba::ip::address_v4::broadcast(), port);            

        socket.send_to(data, senderEndpoint);
        socket.close(error);
    }

相关文章