🇩🇪 Deutsch

17 Nov 2022

Get Hostname on Linux or FreeBSD in C

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.

Kompilieren des Sourcecodes und starten des Programms

  • Funktioniert under GNU/Linux und FreeBSD
$ gcc hostname.c 
$ ./a.out 
Hostname: calcit - Length: 6 

Der Source-Code

#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);
}