How to get the hostname from /etc/hostname & DNS domain name?
Solution 1
When you type
hostname
it will show you the value that is stored in
/etc/hostname
See hostname --help
for a lot of options. From the help ...
-s, --short short host name
-a, --alias alias names
-i, --ip-address addresses for the host name
-I, --all-ip-addresses all addresses for the host
-f, --fqdn, --long long host name (FQDN)
-A, --all-fqdns all long host names (FQDNs)
-d, --domain DNS domain name
-y, --yp, --nis NIS/YP domain name
-b, --boot set default hostname if none available
-F, --file read host name or NIS domain name from given file
This command can get or set the host name or the NIS domain name. You can also get the DNS domain or the FQDN (fully qualified domain name). Unless you are using bind or NIS for host lookups you can change the FQDN (Fully Qualified Domain Name) and the DNS domain name (which is part of the FQDN) in the /etc/hosts file.
So
hostname -f
for the long host name (FQDN).
Solution 2
Presuming you want your local (LAN) IPv4 address....
To avoid your server returning a long string that combines your IPv4 and IPv6 addresses, use this programmatically in a bash script:
LOCALIP=$(hostname -I | awk '{print $1}')
Or type this on the CLI:
hostname -I | awk '{print $1}'
Related videos on Youtube
dada dudu
Updated on September 18, 2022Comments
-
dada dudu over 1 year
How do I get the host name from
/etc/hosts
? by writinghostname
? And what about the dns domain name, how do I get that? How do I get these names through the commandline?-
Melebius over 7 years
-
-
dada dudu over 7 yearsI get: "hostname: Name or service not known"
-
Rinzwind over 7 yearsDo you have something in
/etc/hostname
? That one we here typically edit for apache. example topic: askubuntu.com/a/218499/15811 -
dada dudu over 7 yearsHave tried to cat /etc/hosts I get a localhost which I shouldn't as I run it on a VM
-
Melebius over 7 years@dadadudu
localhost
is just a nickname for “myself” on a network. All computers (including VM’s) can connect to themselves usinglocalhost
address. -
Rinzwind over 7 years@dadadudu the VM I have here has its own name (it is called "test1").
-
dada dudu over 7 yearsbut is localhost the then? And what about the dns domain name? I get the same error
-
dada dudu over 7 yearsWhen I write hostname, it gives me server03
-
David Foerster over 6 yearsThis only works well if the host has only a single IPv4 address. IPv6 hosts typically have multiple IPv6 addresses (one permanent and one or more temporary).
-
MrPotatoHead over 6 yearsRight. That's why the 1st line of my suggestion is, "Presuming you want your local (LAN) IPv4 address...." But to your point, 'hostname' is not always the best tool for IP info. Depends on the goal. The OP was not detailed in his/her question about what they wanted (presumably the FQDN, but that is speculation on my part).