C语言 linux c - 获取服务器主机名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5190553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
linux c - get server hostname?
提问by Joe
Does anyone know a function to get the hostname of the linux server? I don't really want to have to include any headers or compile other libraries, hoping there is a function built in by default. I'm new to c :)
有谁知道一个函数来获取linux服务器的主机名?我真的不想包含任何头文件或编译其他库,希望有一个默认内置的函数。我是 c 的新手 :)
回答by Alain Pannetier
like gethostname()?
That's the name of the machine on which your app is running.
这是运行您的应用程序的机器的名称。
Or read from
或者从
/proc/sys/kernel/hostname
Update
更新
Simple example
简单的例子
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
char hostname[1024];
gethostname(hostname, 1024);
puts(hostname);
return EXIT_SUCCESS;
}
回答by CygnusX1
Some useful information can be found among environment variables. You will need to include (unfortunately) stdlib.hand you will obtain some useful functions
在环境变量中可以找到一些有用的信息。您将需要包含(不幸的是)stdlib.h并且您将获得一些有用的功能
回答by Joep
Building on the answer from Alain Pannetier, you can spare a few bytes by using HOST_NAME_MAX:
根据 Alain Pannetier 的回答,您可以使用 HOST_NAME_MAX 节省几个字节:
#include <limits.h>
...
char hostname[HOST_NAME_MAX+1];
gethostname(hostname, HOST_NAME_MAX+1);
...

