0
votes

I'm having problems with the udp broadcast subsection of an application. I am using boost 1.62.0 under windows 10.

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.

I've attempted to change the endpoint from any() to broadcast(), however this only throws the same error on bind().

I normally program under linux, and this code works on my normal target. So I'm scratching my head as to what I'm doing wrong here. Can anyone give me a poke in the right direction?

1

1 Answers

4
votes

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).

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