17 Nov 2022
Manchmal braucht man in einem C-Programm den Hostnamen. Der ist ganz einfach zu bekommen. Wenn man troztdem auf dem Schlauch steht, hier ein kurzes Beispiel-Programm.
$ gcc hostname.c
$ ./a.out
Hostname: calcit - Length: 6
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
char *hostname = NULL;
int i=0;
const int hlength = 40;
/* get hostname and print */
void main(void)
{
// allocate memory
if ((hostname = (char*)malloc(hlength+1)) == NULL) {
printf("\n\nmalloc failed\n");
exit(-1);
}
// get hostname
gethostname (hostname, hlength);
i = strlen(hostname);
printf ("Hostname: %s - Length: %i \n\n", hostname, i);
}