polar
polar

Reputation: 244

How to print out to standard output a boost::asio::ip::tcp::v4

I am running the c++11 chat example from boost.asio examples and trying to print out the tcp::v4() return value to see what ip address the server is using. There is no to_string function that works on boost::asio::ip::tcp as it does on boost::asio::ip.

Here is the main function from the server.cpp of the chat example:

int main(int argc, char* argv[])
{
  try
  {
    if (argc < 2)
    {
      std::cerr << "Usage: chat_server <port> [<port> ...]\n";
      return 1;
    }

    boost::asio::io_context io_context;

    std::list<chat_server> servers;

    for (int i = 1; i < argc; ++i)
    {
      tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[i]));
      servers.emplace_back(io_context, endpoint);
    }

    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

Upvotes: 2

Views: 1585

Answers (1)

sehe
sehe

Reputation: 393009

There is no to_string function that works on boost::asio::ip::tcp as it does on boost::asio::ip

That's confused. boost::asio::ip::tcp is a class that you never instantiate (it's a static class modelling a protocol), boost::asio::ip is a namespace, you can't expect to print a namespace.

Then, there's a lot of irrelevant code in your sample. Let's for the sake of it assume your chat_server was the one trying to print the end-points:

Live On Coliru

struct chat_server {
    chat_server(boost::asio::io_context&, tcp::endpoint ep) {
        std::cout << "Serving on " << ep << "\n";
    }
};

Prints something like

Serving on 0.0.0.0:100
Serving on 0.0.0.0:110
Serving on 0.0.0.0:120
...

If you really want to take the question title literal, you'd print the address part of the endpoint:

    std::cout << "Serving on " << ep.address() << "\n";

Which prints the slightly useless

Serving on 0.0.0.0
Serving on 0.0.0.0
Serving on 0.0.0.0
...

That's because you didn't bind to an interface. Slightly more useful if you do:

Live On Coliru

        tcp::endpoint endpoint(ip::address_v4::loopback(), std::atoi(argv[i]));
Serving on 127.0.0.1
Serving on 127.0.0.1
Serving on 127.0.0.1

TL;DR

All the code you needed:

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

int main() {
    std::cout << boost::asio::ip::address_v4::loopback() << "\n";
}

Upvotes: 1

Related Questions