Reputation: 1237
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
Upvotes: 16
Views: 6740
Reputation: 9
const staticDnsHttpAgent = (resolvconf) => new http.Agent({
lookup: (hostname, opts, cb) => {
cb(null, resolvconf, undefined)
}
});
resolvconf.push({
address: '<ipv6-address1>',
family: 6,
},
{
address: '<ipv6-address2>',
family: 6,
},
{
address: '<ipv4-address>',
family: 4,
},
)
http.get("http://some-domain.com/whatever", {agent: staticDnsAgent(resolveConf)})
this is a update for newer version of nodejs(22), cb params needs to be an array
Upvotes: 0
Reputation: 2131
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')})
Upvotes: 17
Reputation: 381
There is a tiny module that does exactly that: evil-dns.
evilDns.add('foo.com', '1.2.3.4');
Upvotes: 12
Reputation: 631
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?
Upvotes: 3