MacOS – Force system to use local hosts file before DNS (OS X El Capitan)

dnsmacosNetworkvpn

I want to find a way to force my system to resolve through the local hosts file on my system before it makes a DNS query. There's a reason for this, and here's my context:

  • I live in China. I need a VPN to get to the 'real' Internet. In my case I'm using Astrill.
  • Inside my company, its local DNS points our intranet, wiki and other online resources to local IPs. When outside the company, the DNS entries are obviously those available on external IPs for everyone.

When connected to the VPN, I don't want my machine to look up by public IP, I want to still use the local IP that the local DNS gives me, but all traffic is going through the VPN.

A solution that I thought of was to put the local IPs in a DNS entry in the hosts file.

Then I read about a *nix technique which uses a file called nsswitch.conf to tell the system to always use the file first, then DNS. But OS X doesn't seem to use this (the file doesn't exist in /etc/ anyway).

This would be ideal because then I could always try to use the local resource wherever I am – normal Internet, VPN connection, or inside or outside my company.

I can't find any documentation for OS X support of nsswitch.conf or information about if it automatically checks hosts before DNS anyway.

Best Answer

This is already the default in OS X. I.e. if you specify a host name in the hosts file, lookups will use the IP address you've specified there instead of doing a DNS lookup.

Note that this is only true for programs using the system standard resolver functions. Programs can use their own resolving mechanism that is not guaranteed to honor anything you write in the hosts file. However, those programs should be rare and far between.