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 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

Similar Posts

  • Micosoft招聘部分算法题

    Micosoft招聘部分算法题 1.链表和数组的区别在哪里? 2.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法? 3.编写实现数组排序的一种算法。说明为什么你会选择用这样的方法? 4.请编写能直接实现strstr()函数功能的代码。 5.编写反转字符串的程序,要求优化速度、优化空间。 6.在链表里如何发现循环链接? 7.给出洗牌的一个算法,并将洗好的牌存储在一个整形数组里。 8.写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?) 9.给出一个函数来输出一个字符串的所有排列。 10.请编写实现malloc()内存分配函数功能一样的代码。 11.给出一个函数来复制两个字符串A和B。字符串A的后几个字节和字符串B的前几个字节重叠。 12.怎样编写一个程序,把一个有序整数数组放到二叉树中? 13.怎样从顶部开始逐层打印二叉树结点数据?请编程。 14.怎样把一个链表掉个顺序(也就是反序,注意链表的边界条件并考虑空链表)? 来源:·日月光华 bbs.fudan.edu.cn Read more: Java与C++在语言方面上的不同 Java Calling Native Functions in .DLL on Windows MFC程序使用系统风格界面 Linux UDP Programming Tutorial Getting Process Own Pid in C and C++ Checking Whether a String Starts with Another String in C++ GCC May “Save” You…

  • | | | |

    How to synchronize OneDrive and OneDrive for Business files in Linux using Insync

    OneDrive is one of the good cloud storage services available and there is a business version called OneDrive for Business. Microsoft’s Office 365 plan is widely used including Exchange Email service and OneDrive for Business. However, there is no official client released yet for Linux users. Insync is a third party cloud storage syncing software…

  • |

    How to Match Multiple Lines using Regex in Perl One-liners

    Perl one-liners with perl’s regular expression statement can be a very powerful text processing tools used as commands in a terminal or a script. By default, the input to the perl one-liner with -p or -n options is passed line by line. However, when we want to match multiple lines, it gets us some trouble….

Leave a Reply

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