a blog for those who code

Wednesday, 5 November 2014

Get information from remote servers in Nodejs using DNS module

In this post we will show you how to get information from remote servers in Nodejs using DNS module. Before going further with this post lets take a look at DNS module in Nodejs.

Before going into the code lets look at some of the functions of dns module.

dns.lookup(domain, [family], callback) - It resolves a domain into the first found A (i.e. IPv4) or AAAA (IPv6) record. The family parameter will be either a 4 or a 6 and represents which IP family you wish to query for the address. The callback for the dns.lookup() function will provide an error, address and family parameter if they are available.

dns.resolve(domain, [rrtype], callback) - It resolves a domain into an array of the record types specified by rrtype. Record types([rrtype]) are of the following: 'A','AAAA','MX','TXT','SRV','PTR','NS' ad=nd 'CNAME'. This method can take any of these seven record types as the parameter.

dns.reverse(ipaddress, callback) - It reverses resolves ip address to an array of domain names.

The difference between dns.lookup() and dns.resolve() is that dns.resolve()'s optional second parameter is a record type, i.e. the type of DNS record you want to resolve. As mentioned above there are seven record types and dns.resolve() method can take any of these seven record types as the parameter, but if none are provided it defaults to the 'A' type. dns.resolve() will give you a list of addresses whereas dns.lookup will give you only one record (i.e. first found A or AAAA record).

Code :


var dns = require('dns');
var domain = 'www.google.com';

dns.resolve(domain, function(err, adds) {
if(err) throw err;

adds.forEach(function(add) {
   dns.reverse(add, function(err, domains){
     if(err) {}
     else {
console.log('resolve domain name for '+add+' is '+domain);
}
   });
});
});

dns.lookup(domain, function(err, add) {
if(err) throw err;
  dns.reverse(add, function(err, domains){
    if(err) {}
    else {
console.log('lookup domain name for ' +add+' is '+domain);
    }
   });
});

Output :



Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License