c – boost :: asio UDP广播

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

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) {
}

并希望从我的队列广播消息

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();
}

但是我的代码在第一个代码块中抛出一个异常无效的参数异常.它工作正常127.0.0.1虽然.我究竟做错了什么?

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

    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);
    }
翻译自:https://stackoverflow.com/questions/9310231/boostasio-udp-broadcasting

转载注明原文:c – boost :: asio UDP广播