I have tested hostname
on several servers (RedHat, Ubuntu), and hostname -f
has proven unreliable, returning sometime the short name only (as described in this question).
I can see the fqn in the aliases: hostname -a
(one of the aliases is the fqn I look for), but the order of the aliases is not fixed.
Is there another way to get the fully qualified name reliably, and store it in a bash variable?
I tried this on CentOS5:
host -TtA $SERVERNAME|grep "has address"|awk '{print $1}'
I have to query my DNS in TCP-Mode. If UDP works in your environment leave away the "T" option.
Note: on an Ubuntu guest (VirtualBox) it won't work:
So to cover all the cases:
Here is one way I found the fqn:
In other words, I had to
nslookup
the IP address, which gives me something like:From there, it was just a question of removing what I didn't want, through bash string manipulations.
Maybe there is a simpler way?
Doesn't
hostname --fqdn
work for you?Your method works only if you have correctly configured your hostname, and have the correct dns settings, etc. If you have all that, then you already know your fqdn.
There is no reliable way to get the fqdn. A single IP address can have several fqdn, and a single fqdn can have several IP addresses... and lots of IP don't have any fqdn at all.
If your machine is directly connected to the internet, just use the IP address and make a reverse DNS request:
host 1.2.3.4
But this very often don't give you the desired answer (just try with google for example).
For cross-platform alternative, if you don't mind using python (runs at least on python 2.7 and python 3)
In Ubuntu, you can do
hostname -A
An OS X safe bash only method, which likely won't work other *nix flavors due to variations in command output:
Python is likely your best bet for broad compatibility.