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

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

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 *