Testing domains in /etc/hosts

If you use /etc/hosts to create fake domains on a unix-like system, you’ve probably noticed that these domains don’t show up for the standard DNS debugging tools. Commands like ‘dig’, ‘host’ or ‘nslookup’ all return ‘Domain not found’ for your custom domains, because they all query your nameserver directly, rather than using a system call.

These domains work for your browser, for instance, because your browser uses system calls to do name resolution, which are handled by the operating system and can looked-up in various different places, like /etc/hosts. However sometimes I find it handy to have a simple shell command that works for my custom domain names. Here’s what I use:

alias resolv='perl -MSocket -e '\''@a=gethostbyname(shift); print map({inet_ntoa($_)."\n"} splice(@a, 4));'\'''

Example:

nearlyfree:keith keith$ resolv keith.local
127.0.0.1

You could write this simple program in any language - I chose to write it in Perl.

Here’s another handy command. If you are using Mac OS X, you may find that you need to send a signal to ‘lookupd’, the process that handles name lookups, to make sure your /etc/hosts changes ‘took’. This alias does just that:

alias lookhup="sudo kill -HUP \`ps -ax | awk '/lookupd/{print\$1}' | head -1\`"

Have fun!