Wandering Thoughts archives

2010-02-10

Beware of using Linux's hostname -s switch

The hostname program has a common switch, -s, which is documented (in the Linux version) as:

-s, --short
Display the short host name. This is the host name cut at the first dot.

Although you would not expect it from this description, running 'hostname -s' will do a gethostbyname() and thus often a DNS lookup in most Linux versions of hostname. This can of course fail if your DNS is not working, which winds up with the very peculiar result of hostname failing. And all of this because you innocently decided to trim out any dots that might be present using the most obvious and easiest approach.

(Most scripts don't cope very well with this, partly because the Bourne shell makes it annoyingly difficult to deal with programs failing in command substitutions and partly because come on, who expects hostname to fail?)

Red Hat Enterprise 5, Fedora 8, Ubuntu 6.06 and Ubuntu 8.04 have versions of hostname that behave this way. Fedora 11 has a version that does not, because someone filed a bug about it; unfortunately I can't tell if this has been fixed upstream or if an upstream bug has been filed (or if it would be useful to do so).

The sad conclusion is that for the next several years, if you need the local hostname without any dots on it you should write something like:

hostname | sed 's/\..*//'

instead of using the shorter, nicer hostname -s.

(We found this out the hard way last night, when we had some sort of network issue that made our DNS servers unreachable to some machines while some of our status check scripts were running.)

HostnameSwitchWarning written at 11:59:16; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.