node.jshosts

NodeJS, bypass linux hosts file


Is there a way in NodeJS to bypass linux's /etc/hosts file?

For example, if I have an entry in my hosts file like: 127.0.0.1 example.com

How would I access the 'real' example.com from NodeJS?

I don't want to temporarily modify /etc/hosts to do this, as it can bring about some problems and is not a clean solution.

Thanks in advance!


Solution

  • I didn't think was possible at first but then I stumbled upon a way to ignore the hosts file on Linux. Additionally, I found a DNS API built into Node. Basically, by default, Node defers to the operating system to do a DNS lookup (which will read from /etc/hosts and not make a DNS query at all if it doesn't have to). However, Node also exposes a method to resolve hostnames by explicitly making DNS requests. This will give you the IP address you're looking for.

    $ cat /etc/hosts
    <snip>
    127.0.0.1 google.com
    $ ping google.com
    PING google.com (127.0.0.1) 56(84) bytes of data.
    ...
    

    That shows the host file is definitely working.

    const dns = require('dns')
    
    // This will use the hosts file.
    dns.lookup('google.com', function (err, res) {
      console.log('This computer thinks Google is located at: ' + res)
    })
    
    dns.resolve4('google.com', function (err, res) {
      console.log('A real IP address of Google is: ' + res[0])
    })
    

    This outputs different values as expected:

    $ node host.js
    This computer thinks Google is located at: 127.0.0.1
    A real IP address of Google is: 69.77.145.253
    

    Note that I tested this using the latest Node v8.0.0. However, I looked at some older docs and the API existed since at least v0.12 so, assuming nothing significantly changed, this should work for whatever version of Node you happen to running. Also, resolving a hostname to an IP address might be only half the battle. Some websites will behave strangely (or not at all) if you try accessing them through an IP directly.