【问题标题】:udp broadcast using boost::asio under windowswindows下使用boost::asio进行udp广播
【发布时间】:2016-11-10 17:25:41
【问题描述】:

我在使用应用程序的 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 下编程,这段代码适用于我的正常目标。所以我在挠头,我在这里做错了什么。谁能给我一个正确的方向?

【问题讨论】:

    标签: c++ boost udp boost-asio


    【解决方案1】:

    我相信您想使用 any() 将您的套接字绑定到本地端点(如果您希望接收广播数据包 - 请参阅this question),并使用广播()发送到远程端点(请参阅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;
      }
    }
    

    【讨论】:

    • 谢谢你,这就是我所缺少的。
    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 2018-05-29
    • 2016-07-30
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多