Getting Hostname in C Programs in Linux
Posted on In QAIn 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
missing a “\” in the code between the “s” and “n” in the print statement.
Thanks Dave for pointing this formatting error. We have fixed it.
No you haven’t
A plugin bug removed the `\n`. Removed the plugin.