How to get the hostname of the node in C++?

Posted on In QA

In C++, how to get the hostname of the node?

In C++, the C way works too. However, with Boost, you can use the boost::asio::ip::host_name() function to get the hostname as a std::string:

namespace boost {
namespace asio {
namespace ip {

/// Get the current host name.
BOOST_ASIO_DECL std::string host_name();

...

More at http://www.boost.org/doc/libs/1_63_0/boost/asio/ip/host_name.hpp

One example:

The boost-host-name.cpp

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

namespace ip = boost::asio::ip;

int main()
{
  boost::asio::io_service io_service;

  std::string h = ip::host_name();
  std::cout << "hostname: " << h << 'n';
}

Build and run it:

$ g++ boost-host-name.cpp -o host-name -lboost_system
$ ./host-name
hostname: host001

Leave a Reply

Your email address will not be published. Required fields are marked *