How to get ip Address from hostname?

1.8k Views Asked by At

I have an node.js server application that needs to know the requested ip address in order to do some operation. The problem is that, when the user use /etc/hosts to register an Ip alias to access my server, the req.headers information on the server side shows the ip alias and not the ip requested.

I am using restify to serve my application, I already tried the req.connection but it is still no good.

I need that the javascript from my website knows what is actually the ip alias's ip address (pre-registered in the /etc/hosts) or that my node.js(restify) interprets the real ip_address requested and not the ip alias that the client uses.

Edit1: The main problem on getting the ip address requested on de server (nodejs) is that the requested for this cases is the ALIAS registered on the /etc/hosts. So it arrives at the server as just the named alias and not the ip (my server listens on multiple different IPs)

2

There are 2 best solutions below

1
Jayshree Rathod On

Node JS DNS Documentation. https://nodejs.org/api/dns.html

or check the below link. How to resolve hostname to an ip address in node js

4
ANIK ISLAM SHOJIB On

you can check here https://nodejs.org/api/dns.html#dns_dnspromises_lookup_hostname_options

also try

const dns = require('dns');
const dnsPromises = dns.promises;
const options = {
  family: 6,
  hints: dns.ADDRCONFIG | dns.V4MAPPED,
};

dnsPromises.lookup('example.com', options).then((result) => {
  console.log('address: %j family: IPv%s', result.address, result.family);
  // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
});

// When options.all is true, the result will be an Array.
options.all = true;
dnsPromises.lookup('example.com', options).then((result) => {
  console.log('addresses: %j', result);
  // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
});

check this output section

enter image description here