Node override request IP resolution
Asked Answered
G

3

16

I'm struggling to find the correct terminology to accurately phrase this problem, but I'm gonna give it my best shot:

In node.js, is there a way to manually override the IP address when making an HTTP request (e.g. request some-domain.com/whatever and instead of resolving the IP address through DNS, manually provide some IP address 1.2.3.4) ?

This would, effectively speaking, be the equivalent of setting 1.2.3.4 some-domain.com in /etc/hosts

Groats answered 26/1, 2016 at 23:38 Comment(1)
Did you figure out how to do that?Arachnid
R
12

There is a tiny module that does exactly that: evil-dns.

evilDns.add('foo.com', '1.2.3.4');
Rovelli answered 10/8, 2017 at 12:56 Comment(1)
im try to use this, but doesnt seem to work for me, always return error Uncaught TypeError: net.isIPv4 is not a function in node js for cloudflare workerYester
L
17

Node's http and https modules take an Agent as an argument, and you can override the dns resolver with the lookup parameter.

const http = require("http");
const https = require("https");


const staticLookup = (ip, v) => (hostname, opts, cb) => cb(null, ip, v || 4)
const staticDnsAgent = (scheme, ip) => new require(scheme).Agent({lookup: staticLookup(ip)})

http.get("http://some-domain.com/whatever", {agent: staticDnsAgent('http', '1.2.3.4')})
Lublin answered 9/7, 2020 at 5:49 Comment(2)
This is fantastic. Thank you. Not sure why this solution didn't get more upvotes.Chessman
Thanks! I guess because I posted it 3 years later but yeah I saw the other answers and was convinced there must be a better way.Lublin
R
12

There is a tiny module that does exactly that: evil-dns.

evilDns.add('foo.com', '1.2.3.4');
Rovelli answered 10/8, 2017 at 12:56 Comment(1)
im try to use this, but doesnt seem to work for me, always return error Uncaught TypeError: net.isIPv4 is not a function in node js for cloudflare workerYester
W
3

I'd suggest looking at Nodejs's doc on the DNS API (https://nodejs.org/api/dns.html). You can modify the OS host file and use dns.lookup() to pull from the host file and not do a DNS query.

Not sure if you are trying to avoid modifying the host file?

Wealthy answered 26/1, 2016 at 23:51 Comment(3)
Yes, I would prefer not having to modify the host file (this would save a huge amount of complications)Groats
Can you explain the use case a bit more? Is this for a small number of host names where you want to set static IPs, etc?Wealthy
It's for some remote automation process via HTTP requests to a PHP script, where a domain and IP address are specified but have not always been associated via their appropriate nameserver yet. The reason this request has to specify the domain name is because the server will often be running a multi-site setup.Groats

© 2022 - 2024 — McMap. All rights reserved.