一篇boost asio UDP广播示例。

为什么要广播

通常我们需要在局域网来进行广播来查找主机,广播的意思就是向同网段的全部主机发送数据包。而在广域网是不允许的,可以想象广域网主机数量之多,广播造成网络堵塞。广播只能是udp,是由路由器向所有主机发送数据包,包括发送者本身。如果发送的是本身,可以留意下你收的IP:192.168.56.1。还有个组播的,这个在广域网和局域网都允许。

示例代码

服务器:

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <thread>
void handle_send()
{

};
int main()
{
  namespace ip = boost::asio::ip;
  boost::asio::io_service io_service;

  // Server binds to any address and any port.
  ip::udp::socket socket(io_service,
                         ip::udp::endpoint(ip::udp::v4(), 0));
  socket.set_option(boost::asio::socket_base::broadcast(true));

  // Broadcast will go to port 8888.
  ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), 8888);

  // Broadcast data.
  boost::array<char, 4> buffer;
 // socket.send_to(boost::asio::buffer(buffer), broadcast_endpoint);
  socket.async_send_to(boost::asio::buffer(buffer), broadcast_endpoint,
	  boost::bind(&handle_send));
  io_service.run();
  //std::thread run_thread([&]{ io_service.run(); });
  //run_thread.join();
}

客户端:

#include <iostream>

#include <boost/asio.hpp>
#include <boost/array.hpp>
int main()
{
  namespace ip = boost::asio::ip;
  boost::asio::io_service io_service;

  // Client binds to any address on port 8888 (the same port on which
  // broadcast data is sent from server).
  ip::udp::socket socket(io_service,
                         ip::udp::endpoint(ip::udp::v4(), 8888 ));

  ip::udp::endpoint sender_endpoint;

  // Receive data.
  boost::array<char, 4> buffer;
  std::size_t bytes_transferred =
    socket.receive_from(boost::asio::buffer(buffer), sender_endpoint);

  std::cout << "remote host ip : " << sender_endpoint.address().to_string() << std::endl;
 // std::cout << "got " << bytes_transferred << " bytes." << std::endl;
}

总结

上面的例子是阻塞模式的广播,有兴趣的可以把它修改成异步模式的,记得udp不是可靠的,上面的例子出处来自国外忘记,,。。。