c++boost-asio

Why this example from boost.asio does not work as expected


I'm been reading the examples from the boost.asio docs to have a understanding of how to use it to be able to do more complex networking stuff in c++, but when I try to run this udp client daytime example giving a hostname to run the service "daytime" to receive a response it freezes when receives the data from the socket, stores the data and the length, and the result expected should be that it respond with the current daytime without get freeze doing the constant request of the service for daytime in the hostname passed, and I don't actually know which servers give that service supporting udp request for that service.

So I would like the reason why that happen and get feedback to know more about networking and understand more deeply how to use asio from boost

Edit: sorry if I was not clear, but I tried to set the host name for example: time.google.com to do the request, and I asked to copilot if it could help me and gave a solution, but It changed some things of the code, and worked as expected, but I want to know why exactly this example does not work as expected as the tcp client example with the hostname time.nist.gov, I don't know why so many people get upset so easy, I guess I have no idea about anything I don't know yet, and should not ask about guidance .

#include <array>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: client <host>" << std::endl;
      return 1;
    }

    boost::asio::io_context io_context;

    udp::resolver resolver(io_context);
    udp::endpoint receiver_endpoint =
      *resolver.resolve(udp::v4(), argv[1], "daytime").begin();

    udp::socket socket(io_context);
    socket.open(udp::v4());

    std::array<char, 1> send_buf  = {{ 0 }};
    socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);

    std::array<char, 128> recv_buf;
    udp::endpoint sender_endpoint;
    
    # Where it freezes
    size_t len = socket.receive_from(
        boost::asio::buffer(recv_buf), sender_endpoint);

    std::cout.write(recv_buf.data(), len);
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

Solution

  • You need to point to a host that is actually running an UDP listener (typically, an inetd service for daytime).

    If you don't have one, you can, of course, emulate one. E.g. using netcat on linux:

    sudo nc -ul 13 <<< "fake daytime: $(date)"
    

    Which does work