Getting Hostname in C Programs in Linux

In C, how to get the hostname of the node?

In C, you may use the gethostname function.

    #include <unistd.h>

    int gethostname(char *name, size_t namelen); 

The gethostname() function shall return the standard host name for the current machine. The namelen argument shall specify the size of the array pointed to by the name argument. The returned name shall be null-terminated, except that if namelen is an insufficient length to hold the host name, then the returned name shall be truncated and it is unspecified whether the returned name is null-terminated.

Host names are limited to {HOST_NAME_MAX} bytes.

One example:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <limits.h>

    int main(void) {
      char hostname[HOST_NAME_MAX + 1];
      gethostname(hostname, HOST_NAME_MAX + 1);

      printf("hostname: %s\n", hostname);

      return EXIT_SUCCESS;
    }

Execution result:

    $ gcc a.c -o a
    $ ./a
    hostname: host001

4 comments:

Leave a Reply

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