boost::asio UDP 广播

编程入门 行业动态 更新时间:2024-10-11 09:29:59
本文介绍了boost::asio UDP 广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想使用 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);
    }

这篇关于boost::asio UDP 广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 08:45:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/826323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:boost   asio   UDP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!