3

Let's say I have a Linux server with an external IP of 123.456.789.012 and a local IP of 192.168.0.1. If it's /etc/hosts file looks like, for example,

123.456.789.012 host2.mydomain.com
192.168.0.1 host2.mydomain.com

When an application on the server generates traffic to send using host2.mydomain.com, how does the server know whether to use the local or external IP address (since the same host name shows two IP addresses)?

Or, does it need something additional than what I've presented here to decide this?

Or, does it just sent it out as host2.mydomain.com and let the receiving end deal with it (if so, how to make sure traffic intended for local network indeed goes to local network)?

5 Answers 5

4

From hosts(5):

For each host a single line should be present

So duplicating the same hostname for different IPs is a no-no; behaviour is not guaranteed if you do.

HOWEVER, when I put

1.2.3.4 testhost 
5.6.7.8 testhost 

in /etc/hosts, getent hosts testhost returns both lines.

NOTE that this will of course be highly specific to the OS and libc versions used.

0
1

Your machine, computer1, has an updated hosts file:

123.456.789.012 host2.mydomain.com
192.168.0.1 host2.mydomain.com

Any traffic sent to host2.domain.com from computer1 needs to be resolved to an IP address, and the place that has precedence over all other sources (e.g. DNS) is your /etc/hosts file. The first matching for the hostname in /etc/hosts is used. So, in your example, host2.mydomain.com will always resolve to 123.456.789.012.

2
  • How do you know the first match is used ?
    – adaptr
    Mar 27, 2012 at 15:46
  • I verified experimentally, but I accept that the more correct answer is that it is undefined. You most certainly should not rely on it matching the first entry.
    – Lunar_Lamp
    Mar 27, 2012 at 15:55
1

It doesn't.

You should either use seperate internal/external domain names, or use DNS to provide different responses based on network location.

1

Linux man page clearly says that "one line per IP address", so what you are doing is undefined. You can get the first one in the file, the last, or random.

It is better for your application just to use the ip in this case, maybe based on some criteria.

1
  • sorry, i pasted less than i intended. it also says: For each host a single line should be present. But after reviewing this question more and reading comments/answers from others, I realize that this may be os and even version-dependent. Mine is ubuntu lucid.
    – johnshen64
    Mar 27, 2012 at 16:03
1

You would have a local dns server & a remote DNS server. So on the machine in hosts you just have the IP you want it to use.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .