How to get the hostname of the node in C?

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

asked May 29, 2017 by dtivl (2,500 points)

1 Answer

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
answered May 29, 2017 by dtivl (2,500 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost