linux c - get server hostname?

前端 未结 3 1736
南笙
南笙 2021-02-14 18:25

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 b

相关标签:
3条回答
  • 2021-02-14 18:49

    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;
    }
    
    0 讨论(0)
  • 2021-02-14 18:52

    Building on the answer from Alain Pannetier, you can spare a few bytes by using HOST_NAME_MAX:

    #include <limits.h>
    ...
      char hostname[HOST_NAME_MAX+1];
      gethostname(hostname, HOST_NAME_MAX+1);
    ...
    
    0 讨论(0)
  • 2021-02-14 19:09

    Some useful information can be found among environment variables. You will need to include (unfortunately) stdlib.h and you will obtain some useful functions

    0 讨论(0)
提交回复
热议问题