简体   繁体   English

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

[英]udp broadcast using boost::asio under windows

I'm having problems with the udp broadcast subsection of an application. 我在应用程序的udp广播小节中遇到问题。 I am using boost 1.62.0 under windows 10. 我正在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;
  }
}

I receive: send_to: The requested address is not valid in its context From the catch. 我收到:send_to:请求的地址在其上下文中无效。

I've attempted to change the endpoint from any() to broadcast(), however this only throws the same error on bind(). 我试图将端点从any()更改为broadcast(),但是这只会在bind()上引发相同的错误。

I normally program under linux, and this code works on my normal target. 我通常在linux下编程,并且此代码可以在我的正常目标上运行。 So I'm scratching my head as to what I'm doing wrong here. 所以我在这里弄错了我的头。 Can anyone give me a poke in the right direction? 谁能给我正确的方向戳?

I believe you want to bind your socket to a local endpoint with any() (if you wish to receive broadcast packets - see this question ), and send to a remote endpoint using broadcast() (see this question ). 我相信您想使用any()将套接字绑定到本地端点(如果您希望接收广播数据包-请参阅此问题 ),并使用broadcast()发送到远程端点(请参阅此问题 )。

The following compiles for me and does not throw any errors: 以下代码为我编译,不会引发任何错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM