Does anyone know a function to get the hostname of the linux server? I don't really want to have to include any headers or compile other libraries, hoping there is a function built in by default. I'm new to c :)
1. hostname command without any option/argument shows the hostname of the machine as returned by the gethostname(2) function. 2. When called with one argument or with the --file option, the commands set the host name or the NIS/YP domain name.
Locating Your Computer's Hostname on a PC (Windows 10)In the window the window that appears on the bottom-left hand corner of your screen, type in cmd and click OK. The command prompt window will appear. In this window, type hostname and press Enter. The name of your computer will be displayed.
A far simpler and more common way to look up the hostname from an IP address is to use nslookup. Nslookup is a command-line utility, similar to dig, but that allows users to query DNS for hostnames and IP address mappings.
Building on the answer from Alain Pannetier, you can spare a few bytes by using HOST_NAME_MAX:
#include <limits.h>
...
char hostname[HOST_NAME_MAX+1];
gethostname(hostname, HOST_NAME_MAX+1);
...
like gethostname() ?
That's the name of the machine on which your app is running.
Or read from
/proc/sys/kernel/hostname
Update
Simple example
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
char hostname[1024];
gethostname(hostname, 1024);
puts(hostname);
return EXIT_SUCCESS;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With