Home Web Front-end JS Tutorial How to use DNS module in Node.js (detailed tutorial)

How to use DNS module in Node.js (detailed tutorial)

Jun 02, 2018 pm 05:23 PM
javascript node.js detailed

This article introduces the relevant knowledge points of the DNS module in Node.js in detail, and shares the relevant example code. Interested friends can refer to it.

1. DNS

In Node.js, the DNS module is provided to implement domain name search and domain name resolution processing.

  • In the DNS module, three main methods and a series of convenient methods are provided.

  • resolve method: used to resolve a domain name into a set of DNS records.

  • reverse method: Used to convert an IP address into a set of domain names.

  • lookup method: Used to convert a domain name into an IP address.

  • The other convenience methods in the DNS module are a convenient form of the resolve method.

#2. Use the resolve method to resolve the domain name into a DNS record

`DNS.resolve(domain, [rrtype ], callback(err, address){...})`

The domain parameter is a string, used to specify the domain name that needs to be resolved, and can include subdomain names.
The rrtypr parameter is a string used to specify the record type to be obtained. The record types that can be specified are as follows.

  • A, this parameter value is the default value. When the record type is A, the record maps an IPv4 address to a domain name.

  • AAAA, when the record type is AAAA, this record maps an IPv6 address to a domain name.

  • CNAME, when the record type is CNAME, it means that the record is an alias record of a domain name. For example, a www.example.com domain name record may be an example.com domain name record. Alias ​​record.

  • MX, the MX record points to a mail server in a domain that uses SMTP. For example, when you want to send an email to the person@domain.com email address, the MX of the domain.com domain The record contains the email server address from which the email was sent.

  • TXT, TXT record is the description record attached to the domain name.

  • SRV, SRV records are used to provide information for all available services in a specific domain.

  • PTR, PTR record is used for reverse address resolution. This record maps a domain name to an IPv4 address.

  • NS, NS (Name Server) records are domain name server records, used to specify which DNS server resolves the domain name.

The callback function has two parameters. err is the error object triggered when domain name resolution fails. The addresses parameter is an array that stores all obtained DNS records.

3. Various convenient methods customized for the resolve method

  • DNS.resolve4(domain, callback), Get the IPv4 address

  • DNS.resolve6(domain, callback), get the IPv6 address

  • DNS.resolveMx(domain, callback), get the MX Records, mail exchange server records

  • DNS.resolveTxt(domain, callback), obtains TXT records, domain name attached description records

  • ##DNS. resolveSrv(domain, callback), get SRV records, service records

  • DNS.resolveNs(domain, callback), get NS records, domain name server records

  • DNS.resolveCname(domain, callback), get the alias record

4. Use the lookup method to query the IP address

When using the resolve4 method or resolve6 method, because the addresses parameter value array in the callback parameter value callback function stores all obtained IPv4 addresses or IPv6 addresses. Therefore, the DNS module provides a lookup method to obtain the first discovered IPv4 address or IPv6 address


`DNS.lookup(domain, [family], callback(err, addresses, family) {...})`

  • The domain parameter is a string, used to specify the domain name to be resolved

  • The family parameter value is one Integer value, used to specify the type of IP address to be obtained. The parameter value that can be specified is 4 or 6. The default parameter value is null, which means that both IPv4 and IPv6 can be obtained

  • The err parameter value of the callback function is the error object triggered when the address fails to be obtained. When the domain name does not exist or the query fails, the code attribute value of the error object is ENOENT

  • The addresses parameter value is one A string, which is the obtained IP address

  • When the family parameter value is 4, it is represented as an IPv4 address; when it is 6, it is represented as an IPv6 address.

5. Use the reverse method to reversely resolve an IP address

In the DNS module, use the reverse method to reverse an IP address. The direction is resolved to a set of domain names bound to the IP address


`DNS.reverse(ip, callback(err, domains){...})`

  • The ip parameter value is a string, used to specify the IP address that needs to be resolved

  • The err of the callback function is the error object after the reverse resolution address fails

  • The domains parameter value is an array, which stores all obtained domain names

6. Various error codes in the DNS module

The err parameter value is the error object triggered when performing various parsing or reverse parsing operations. You can determine what error occurred based on the code attribute value of the error object, that is, the triggered error code

  • ENODATA: The DNS server returned a query result with no data

  • EFORMERR: The DNS server found that the client used malformed query parameters when requesting a query

  • ESERVFAIL: The DNS server failed to perform the query operation

  • ENOTFOUND: No domain name found

  • ENOTIMP: The DNS server cannot perform the query operation requested by the client

  • EREFUSED: The DNS server refused to perform the query operation

  • EBADQUERY: Malformed DNS query

  • EBADNAME: Domain name format is incorrect

  • EBADFAMILY: Unsupported IP address type

  • EBADRESP: Malformed DNS reply

  • ECONNREFUSED: Unable to establish Connection to DNS server

  • ETIMEOUT: Timeout to establish connection to DNS server

  • EEOF: Bottom of file reached

  • EFILE: Failed to read file

  • ENOMEM: Not enough memory space

  • EDESTRUCTION: Channel already Destroyed

  • EBADSTR: String format error

  • EBADFLAGS: Wrong judgment flag specified

  • ENONAME: The specified host name is not in numeric format

  • EBADHINTS: The specified prompt flag is invalid

  • ENOTINITIALIZED: c-ares class library Initialization has not been completed

  • ELOADIPHLPAPI: An error was triggered while loading iphlpapi.dll

  • EADDREGETNETWORKPARAMS: GetNetworkParams function not found

  • ECANCELLED: DNS query operation was canceled

7. Basic use of DNS module

const dns = require('dns');
let url = 'www.qq.com';

dns.resolve(url, 'A', (err, addresses) => {
  console.log(addresses);
  // IPv4地址 [ '103.7.30.123' ]
});

dns.resolve(url, 'AAAA', (err, addresses) => {
  console.log(addresses);
  // IPv6地址 [ '240e:e1:8100:28::2:16' ]
});
dns.resolveMx('qq.com', (err, addresses) => {
  console.log(addresses);
  // 邮件交换服务器记录
  // [ { exchange: 'mx2.qq.com', priority: 20 },
  //  { exchange: 'mx1.qq.com', priority: 30 },
  //  { exchange: 'mx3.qq.com', priority: 10 } ]
  
});

dns.resolveTxt('qq.com', (err, addresses) => {
  console.log(addresses);
  // 域名附加的描述记录
  // [ [ 'v=spf1 include:spf.mail.qq.com -all' ] ]
});

dns.resolveSrv('www.baidu.com', (err, addresses) => {
  console.log(addresses);
  // 服务记录
  // []
});

dns.resolveNs('www.github.com', (err, addresses) => {
  console.log(addresses);
  // 域名服务器记录
  // [ 'ns-421.awsdns-52.com',
  // 'ns-520.awsdns-01.net',
  // 'ns1.p16.dynect.net',
  // 'ns2.p16.dynect.net',
  // 'ns3.p16.dynect.net',
  // 'ns4.p16.dynect.net',
  // 'ns-1283.awsdns-32.org',
  // 'ns-1707.awsdns-21.co.uk' ]
});

dns.resolveCname('www.163.com', (err, addresses) => {
  console.log(addresses);
  // 获取别名记录
  // [ 'www.163.com.lxdns.com' ]
});


dns.lookup('google.com', 4, (err, address, family) => {
  // 查询IP地址
  // address,查询到的地址
  // family,IPv4或IPv6
  console.log(address);// 172.217.27.142
  console.log(family);// 4
});

dns.lookup('google.com', 6, (err, address, family) => {
  console.log(address);// 2404:6800:4008:803::200e
  console.log(family);// 6
});

dns.reverse('203.188.200.67', (err, domain) => {
  // 反向解析IP地址
  console.log(domain);
  // [ 'media-router-fp1.prod.media.vip.tp2.yahoo.com' ]
});
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

vue-router related basic knowledge and working principles

axios post submission formdata example

Methods of using axios in vue components

##

The above is the detailed content of How to use DNS module in Node.js (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles