Determining the User IP Address in Node

Node.jsServer Side ProgrammingProgramming

Node.js is a completely open source technology that runs on JavaScript runtime environment. When the users want to access a website or link, they connect with the link using their system IP. We can use the dns.lookup() method in Node to find the IP address of the current user.

Syntax

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

Parameters

The parameters are described below −

  • hostname − This input parameter consists of the web link which is valid or active.

  • options − Default is 0. It takes input for the IP type, i.e., 4 for Ipv4 and 6 for Ipv6.

  • callback − Handles any error if it occurs

Example 1

Create a file with the name "ipAddress.js" and copy the following code snippet. After creating the file, use the command "node ipAddress.js" to run this code.

 Live Demo

// Getting IP of user

// Importing the DNS module
const dns = require('dns');

// Pass the user DNS for which IP is needed
dns.lookup('www.tutorialspoint.com',
(err, addresses, family) => {
   // Print the IP address of user
   console.log('IP Address : ', addresses);
   // Print the number of families found
   console.log('IP Family: ', family);
});

Output

C:\home\node>> node ipAddress.js
IP Address: 117.18.237.42
IP Family: 4
raja
Published on 18-Aug-2021 08:15:34
Advertisements