Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform a DNS lookup to resolve a hostname to an IP address using JavaScript

Tags:

javascript

dns

Is it possible to resolve a hostname using Javascript?

Here would be hypothetical code:

var hostname = "www.yahoo.com";
var ipAddress = DnsLookup(hostname);
console.log(ipAddress);

I am looking for that magic DnsLookup() function. :-)

like image 386
Amir Avatar asked Aug 18 '11 19:08

Amir


2 Answers

There's a relatively new (2018) proposed Internet standard called DNS over HTTPS (also called DoH) that's been taking off. It allows you to send wireformat DNS queries over HTTPS to "DoH servers". The nice thing is, with DoH you get the whole DNS protocol on top of HTTPS. That means you can obtain a lot useful information.

That being said, there's an open source JavaScript library called dohjs that makes it pretty easy to do a DNS lookup in the browser. Here's a quick example code snippet:

const resolver = new doh.DohResolver('https://1.1.1.1/dns-query')
resolver.query('www.yahoo.com')
  .then(console.log)
  .catch(console.error);

Full disclosure: I'm a contributor to dohjs.

There are a lot of resources on cURL's DNS over HTTPS wiki page including a list of public DoH servers and a list of DoH tools (mainly server and client software).

like image 151
kimbo Avatar answered Oct 16 '22 19:10

kimbo


While there is no standard DNS functionality in JavaScript, you can always call a 3rd party public API that does DNS resolution.

For example, Encloud provides such an API, and you can make an XMLHttpRequest for it:

var oReq = new XMLHttpRequest();
oReq.onload = function () {
  var response = JSON.parse(this.responseText);
  alert(JSON.stringify(response.dns_entries));
}  
oReq.open("get", "https://www.enclout.com/api/v1/dns/show.json?auth_token=rN4oqCyJz9v2RRNnQqkx&url=stackoverflow.com", true);
oReq.send();

Of course, you should get your own Auth token. Free Enclout accounts are limited to 6 request per minute.

If you just want the IP, make a GET request for http://api.konvert.me/forward-dns/yourdomain.com.

like image 39
Dan Dascalescu Avatar answered Oct 16 '22 21:10

Dan Dascalescu