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

时间:2016-11-10 17:25:42

标签: c++ boost udp boost-asio

我遇到了应用程序的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下编程,这段代码适用于我的正常目标。所以我在这里弄错了我的错误。任何人都可以给我一个正确的方向戳?

1 个答案:

答案 0 :(得分:3)

我相信您希望使用any()将套接字绑定到本地端点(如果您希望接收广播数据包 - 请参阅this question),并使用broadcast()发送到远程端点(请参阅{{ 3}})。

以下为我编译并且不会抛出任何错误:

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