Open In App

How to determine the user IP address using node.js ?

Node.js is an open-source, back-end JavaScript runtime environment that runs on the web engine and executes JavaScript code. There are various platforms such as Windows, Linux, Mac OS  where Node.js can run. The Domain Name System is a hierarchical and decentralized naming system for computers etc that are connected to the Internet. To find the IP address of the user in Node.js we use dns.lookup() method of dns module.

dns.lookup() function:



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

Parameters:

  1. Hostname: It consists website link which is valid or active.
  2. Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses.
  3. Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error.

Approach to determine IP address:



  1. Import dns module in the node.js file.
  2. Use dns.lookup() function to search for addresses and family of the client.
  3. Display address and family.

Implementation:




// Import file
const dns = require('dns');
  
// dns.lookup() function searches
// for user IP address and family
// if there is no error
dns.lookup('www.geeksforgeeks.org'
(err, addresses, family) => {
  
    // Print the address found of user
    console.log('addresses:', addresses);
  
    // Print the family found of user  
    console.log('family:', family);
});

Run  index.js file using the below command:

node client_ip.js

Output:

Reference:
https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback

Article Tags :