在标准C++中是否有一种可移植的方法来检索主机名

Is there a portable way in standard C++ to retrieve hostname?

本文关键字:可移植 一种 方法 主机 检索 C++ 标准 是否      更新时间:2024-05-10

我正在开发一个C++程序,该程序需要使用它正在运行的计算机的主机名。我目前检索该程序的方法是通过如下方式破坏C API:

char *host = new char[1024];
gethostname(host,1024);
auto hostname = std::string(host);
delete host;

有没有一种可移植的现代C++方法可以做到这一点,而不包括大型外部库(例如boost(?

不,没有标准的C++支持。您要么必须创建自己的函数,要么获得一个具有此功能的库。

#include <string>
//#include <winsock.h>      //Windows
//#include <unistd.h>       //Linux
std::string GetHostName(void)
{
std::string res = "unknown";
char tmp[0x100];
if( gethostname(tmp, sizeof(tmp)) == 0 )
{
res = tmp;
}
return res;
}
相关文章: