Is it possible to use multiple IP addresses for the same host name in a linux hosts file?

The scenario is I have a machine that can be accessed both locally (when I am in the same network as the machine) and publicly (when I am on any external network). I want my hosts file to look something like this:

10.11.82.40 master.parallel.edu master
123.90.132.98 master.parallel.edu master

So that the system will first try the first IP address, and if that doesn't work, try the next one. Is this possible and advisable?

1

2 Answers

Normally IP adress resolving is done via dedicated name services like dnsmasq, bind etc.

The local hosts file /etc/hosts is generally only used if you have a small internal network - listing all internal hosts and their respectives ip addresses; otherwise it should just contain your server's local name (and localhost).

One solution to your question could be to use your server's name in different subdomains, e.g. master.exernal.example.com and master.internal.example.com; now to address master from the external network you have to make external.example.com your primary search domain in /etc/resolv.conf:

# /etc/resolv.conf at external host
search external.example.com example.com
nameserver ns.example.com
# /etc/resolv.conf at internal host
search internal.example.com example.com
nameserver ns.example.com

(asssuming you have a nameserver at ns.example.com)

In each zone file for .external. and .internal.example.com the hostname points to the respective ip address

# zonefile external network
$ORIGIN external.example.com.
master IN A 123.90.132.98
# zonefile internal network
$ORIGIN internal.example.com.
master IN A 10.11.82.40

This way you can use curl within each network without bothering with FullQualifiedDomainNames.

Yes, it is and always has been possible to have more than one IP address for a hostname. Note that while gethostbyname returns only one mapping (generally the first found in /etc/hosts), in modern Unix you can use getaddrinfo to walk through the entries. Applications should - but often do not - walk through the entries when making a connection. But ... lazy programmers often do not write for this case.

This is a ancient feature in Unix networking, but often not properly used by programmers.

In my work I use a simple wrapper C++ class to walk through the entries when making a connection, so usage is simple, and I get the full behavior.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like