boost::asio UDP broadcasting(boost::asio UDP 广播)
问题描述
我想使用 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 广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:boost::asio UDP 广播
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
