How to alias a hostname?

5

2

Is it possible to keep a network alias - without specifying the IP address in the hosts file? For instance, I have abcd.efgh.com but want abcd -> abcd.efgh.com so that ping and ssh work as they normally would.

I want it to work with dynamic IP on abcd.efgh.com, that's why I don't want to state the IP address explicitly.

Jonas Byström

Posted 2010-05-28T09:02:25.077

Reputation: 467

Answers

6

A slightly less convienent way is to set up aliases for both ping and ssh, for example:

alias pingfoo="ping foohost.domain.tld"

OpenSSH supports adding hostname aliases (and many more options) to ~/.ssh/config:

Host foo
    Hostname foohost.domain.tld
    # You can also add User, Port, every possible ssh(1) option.

user1686

Posted 2010-05-28T09:02:25.077

Reputation: 283 655

Excellent; I can do without ping now that I think of it, 99.9 % of my use is ssh. – Jonas Byström – 2010-05-28T12:08:16.280

4

With dnsmasq's option --cname=<cname>,<target> you can make a CNAME that indicates that <cname> is actually <target>. Note that this works only if the DNS name of <target> is known to dnsmasq (either in hosts file or through DHCP).

If dnsmasq doesn't work, Unbound is a DNS resolver that supports also unknown targets in a similar situation.

Jawa

Posted 2010-05-28T09:02:25.077

Reputation: 3 349

That's in DNS, not in the hosts file. – mpez0 – 2010-05-28T11:05:34.920

@mpez0: It would still work (dnsmasq is intended to be run on one's LAN or a personal computer, as a caching DNS resolver) – user1686 – 2012-10-10T16:08:12.010

2

If your OS uses GNU glibc, you can use its $HOSTALIASES feature.

From the manual page of gethostbyname(3):

DESCRIPTION

       [etc etc etc] If name doesn't end in a dot and the environment variable
       HOSTALIASES is set, the alias file pointed to by HOSTALIASES will first
       be searched for name (see hostname(7) for the file format). The current
       domain and its parents are searched unless name ends in a dot.

This works with both gethostbyname() and the newer getaddrinfo(); however, it doesn't seem to affect ping at all...

user1686

Posted 2010-05-28T09:02:25.077

Reputation: 283 655

It doesn't affect ping because ping has setuid set and HOSTALIASES only works with executables that don't have this flag. If you already are root it works, but not when using ping as a normal user. – Boris – 2015-06-04T14:15:44.433

Can't alias hostname to IP address. – mightyiam – 2015-08-10T09:45:36.917

Unfortunately not using libc. – Jonas Byström – 2010-05-28T12:06:42.730