search
HomeWeb Front-endJS TutorialNodejs learning to understand the domain name resolution module DNS

Nodejs learning to understand the domain name resolution module DNS

This article will introduce the domain name resolution module DNS in detail. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Related recommendations: "nodejs Tutorial"

Working Principle

Open the browser and go to The moment you enter the URL in the address bar above and press Enter, a lot of things happen. First of all, the computer only understands 0 and 1, which means that the computer does not understand human alphabetical addresses. It only understands IP addresses. If it is IPv4, it is four groups of 8-bit binary numbers. For human convenience, there needs to be a service that translates URLs into IP addresses, which is DNS

The entire DNS acquisition process is cached layer by layer

## 1 , The browser searches its own DNS cache

The browser DNS cache time has nothing to do with the TTL value returned by the DNS server.

After the browser obtains the actual IP address of the website domain name, it will cache its IP to reduce the loss of network requests. Each browser has a fixed DNS cache time, of which Chrome's expiration time is 1 minute. During this period, DNS will not be re-requested

It is more convenient for Chrome browser to check its own DNS cache time. Enter

chrome://net-internals/#dns

## in the address bar 2. Search the operating system’s own DNS cache

3. Read the local HOST file. The path under Windows is generally

c:\Windows\System32\drivers\etc\hosts

 4. Initiate a DNS system call to the broadband operator ISP, and the ISP server will check its own cache

 5. If it is not found yet, the ISP server will replace it The local computer initiates an iterative DNS resolution request

6. If it still fails, the resolution fails

Local resolution The dns module contains two types of functions, one of which is a function that uses underlying operating system tools to perform domain name resolution and does not require network communication. There is only one such function: dns.lookup()

[dns.lookup(hostname[, options], callback)】

This method resolves the domain name (such as 'cnblogs.com') The first record found is A (IPV4) or AAAA (IPV6). Parameter options can be an object or an integer. If no options are provided, both IP v4 and v6 addresses are acceptable. If options is an integer, it must be 4 or 6

The options parameter contains the following attributes

family:地址协议族,必须为4或6的整数
hints:设置getaddrinfo的标志,dns.ADDRCONFIG 或者 dns.V4MAPPED(ipv4映射成ipv6)
all:false(默认),布尔值,如设置为true,则返回IP数组,否则返回单个IP地址
{
  family: 4,
  hints: dns.ADDRCONFIG | dns.V4MAPPED
}

The callback function contains parameters (err, address, family). The address parameter represents an IP v4 or v6 address. The family parameter is 4 or 6, indicating the address family (not necessarily the value passed into lookup before). When an error occurs, the parameter err is the Error object, and err.code is the error code

[Note] err.code is equal to 'ENOENT', which may be because the domain name does not exist, or other reasons, such as no available files. Descriptor

var dns = require('dns');
dns.lookup('www.cnblogs.com', function(err, address, family){
    console.log(err);//null
    console.log(address);//218.11.2.249
    console.log(family);//4});

The same domain name may correspond to multiple different IPs. You can obtain it by setting options = {all: true}

var dns = require('dns');
dns.lookup('www.qq.com',{all:true}, function(err, address, family){
    console.log(err);//null/*[ { address: '125.39.240.113', family: 4 },
  { address: '61.135.157.156', family: 4 } ] */
    console.log(address);
    console.log(family);//undefined});

[dns.lookupService(address, port, callback)]

Corresponding to lookup, the lookupService() method performs the following steps from the IP address And reverse resolution from port to domain name

The parameters of the callback function of this method are (err, hostname, service). hostname and service are both strings (such as 'localhost' and 'http'). When an error occurs, the parameter err is the Error object, and err.code is the error code

var dns = require('dns');
dns.lookupService('127.0.0.1',80,function(err, hostname, service){
    console.log(err);//null
    console.log(hostname);//bai
    console.log(service);//http});

Network analysis Except for dns.lookup() All functions in the dns module need to connect to the actual DNS server for domain name resolution, and always use the network to perform DNS queries

[dns.resolve(hostname[, rrtype], callback)]

This method parses a domain name (such as 'cnblogs.com') into an array of rrtype specified record types

The valid rrtypes value is:

'A' (IPV4 地址, 默认)'AAAA' (IPV6 地址)'MX' (邮件交换记录)'TXT' (text 记录)'SRV' (SRV 记录)'PTR' (用来反向 IP 查找)'NS' (域名服务器 记录)'CNAME' (别名 记录)'SOA' (授权记录的初始值) 

The callback parameter is

(err, addresses)

. The type of each item in addresses depends on the record type. When an error occurs, the parameter err is the Error object, and err.code is the error code <pre class='brush:php;toolbar:false;'>var dns = require(&amp;#39;dns&amp;#39;); //IPV4 dns.resolve(&amp;#39;www.qq.com&amp;#39;,function(err,address){ console.log(address);//[ &amp;#39;125.39.240.113&amp;#39;, &amp;#39;61.135.157.156&amp;#39; ] }); //IPV6 dns.resolve(&amp;#39;www.qq.com&amp;#39;,&amp;#39;AAAA&amp;#39;,function(err,address){ console.log(address);//[ &amp;#39;240e:e1:8100:28::2:16&amp;#39; ] }); //别名 dns.resolve(&amp;#39;www.qq.com&amp;#39;,&amp;#39;CNAME&amp;#39;,function(err,address){ console.log(address);//undefined });</pre>[dns.resolve4(hostname, callback)]

Similar to dns.resolve(), only IPv4 (A record) can be queried

var dns = require('dns');
dns.resolve4('www.qq.com',function(err,address){
    console.log(address);//[ '125.39.240.113', '61.135.157.156' ]
    });

【dns.reverse(ip, callback)】

This method is used for reverse To resolve the IP address, return the domain name array pointing to the IP address. Callback function parameters (err, hostnames). When an error occurs, the parameter err is the Error object, and err.code is the error code

var dns = require('dns');
dns.reverse('114.114.114.114',function(err,hostnames){
    console.log(hostnames);//'public1.114dns.com'
    });

For more programming-related knowledge, please visit:

Programming Teaching

! !

The above is the detailed content of Nodejs learning to understand the domain name resolution module DNS. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

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.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function