在 windows 下使用 boost::asio 进行 udp 广播

udp broadcast using boost::asio under windows

我在使用应用程序的 udp 广播部分时遇到问题。我在 windows 10 下使用 boost 1.62.0。

void test_udp_broadcast(void)
{
  boost::asio::io_service io_service;
  boost::asio::ip::udp::socket socket(io_service);
  boost::asio::ip::udp::endpoint remote_endpoint;

  socket.open(boost::asio::ip::udp::v4());
  socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
  socket.set_option(boost::asio::socket_base::broadcast(true));
  remote_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::any(), 4000);

  try {
    socket.bind(remote_endpoint);
    socket.send_to(boost::asio::buffer("abc", 3), remote_endpoint);
  } catch (boost::system::system_error e) {
    std::cout << e.what() << std::endl;
  }
}

我收到: send_to: 请求的地址在其上下文中无效 从捕获。

我试图将端点从 any() 更改为 broadcast(),但这只会在 bind() 上引发相同的错误。

我通常在 linux 下编程,这段代码适用于我的正常目标。所以我很想知道我在这里做错了什么。谁能给我一个正确方向的戳?

我相信您想使用 any() 将套接字绑定到本地端点(如果您希望接收广播数据包 - 请参阅 this question), and send to a remote endpoint using broadcast() (see this question)。

以下为我编译并且没有抛出任何错误:

void test_udp_broadcast(void)
{
  boost::asio::io_service io_service;
  boost::asio::ip::udp::socket socket(io_service);
  boost::asio::ip::udp::endpoint local_endpoint;
  boost::asio::ip::udp::endpoint remote_endpoint;

  socket.open(boost::asio::ip::udp::v4());
  socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
  socket.set_option(boost::asio::socket_base::broadcast(true));
  local_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::any(), 4000);
  remote_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::broadcast(), 4000);

  try {
    socket.bind(local_endpoint);
    socket.send_to(boost::asio::buffer("abc", 3), remote_endpoint);
  } catch (boost::system::system_error e) {
    std::cout << e.what() << std::endl;
  }
}