简体   繁体   English

linux c - 获取服务器主机名?

[英]linux c - get server hostname?

Does anyone know a function to get the hostname of the linux server?有谁知道一个函数来获取linux服务器的主机名? 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 :)我是 c 的新手 :)

like gethostname() ?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;
}

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);
...

Some useful information can be found among environment variables.在环境变量中可以找到一些有用的信息。 You will need to include (unfortunately) stdlib.h and you will obtain some useful functions您将需要包含(不幸的是) stdlib.h并且您将获得一些有用的功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM