Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux c - get server hostname?

Tags:

c

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 :)

like image 658
Joe Avatar asked Mar 04 '11 06:03

Joe


People also ask

How do I find the hostname of a Unix server?

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.

How do I use Gethostname?

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.

How do you find the hostname of an IP Linux?

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.


2 Answers

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 image 69
Joep Avatar answered Oct 06 '22 02:10

Joep


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;
}
like image 28
Alain Pannetier Avatar answered Oct 06 '22 03:10

Alain Pannetier