search
HomeWeb Front-endJS TutorialHow 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
javascriptnode.jsdetailed

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' ]
});

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
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools