Resolve a domain name with /etc/hosts only if in local network

1

I would like to link mydomain.com to 192.168.1.X only if I'm connected to my local network. Otherwise, I would like to let the DNS servers resolve it (if I'm outside my network).

Now, when I do a ping mydomain.com, it tries to connect to 192.168.1.X wherever I am, because I have the line 192.168.1.22 mydomain.com in my /etc/hosts file.

ryancey

Posted 2014-04-26T15:06:59.743

Reputation: 143

You could certainly do something weird with scripting but I wouldn't recommend it. An approach as proposed by joeqwerty makes sense. Instead of going for a fully blown DNS server you might just maintain such an entry in the router that usually provides the DNS for small home office setups if your device supports that. – binaryanomaly – 2014-04-26T15:48:10.353

Answers

1

You'll need to use an internal DNS server on your network to host a DNS zone for mydomain.com. Then when you're connected to your internal network mydomain.com will be resolved by your internal DNS server (assuming that you're using a DHCP server internally and that you're computer is configured to use DHCP for it's ip address configuration and that the DHCP server is configured to provide your internal DNS server to you via DHCP). When you're not connected to your internal network mydomain.com will be resolved by whatever DNS servers you're using on those other networks.

The problem with using the Hosts file is that it takes precedence over the DNS servers configured in your client TCP/IP configuration, so mydomain.com will always resolve to what is in the Hosts file, regardless of what network you're connected to.

joeqwerty

Posted 2014-04-26T15:06:59.743

Reputation: 5 259

Thank you, even if I think I won't be setting up my own DNS server. It doesn't worth it regarding what I want to do, I will just access my home server from the public URL (slower but easily maintainable). – ryancey – 2014-04-28T10:47:18.587

-1

Create a second HOSTS file that's blank. Create a script to have one replace the other:

  • HOSTS -> HOSTStmp
  • HOSTS2 -> HOSTS
  • HOTSTtmp -> HOSTS2

Run script as needed to toggle between HOSTS files (and maybe also have the script reset the network interfaces).

Ƭᴇcʜιᴇ007

Posted 2014-04-26T15:06:59.743

Reputation: 103 763