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

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

asked May 29, 2017 by dtivl (2,500 points)

1 Answer

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
answered May 29, 2017 by dtivl (2,500 points)

Please log in or register to answer this question.

Related questions

1 answer
asked May 29, 2017 by dtivl (2,500 points)
1 answer
1 answer
0 answers
1 answer
1 answer
asked May 29, 2017 by dtivl (2,500 points)
1 answer
Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...