Getting IP address and type in Node js
In this post, you will learn how to get the IP address and its type by using Node js.
IP (Internet Protocol) addresses are used to identify hardware devices on a network. It is a unique address that identifies a device on the internet or a local network. The internet needs a way to differentiate between different computers, routers, and websites. IP addresses give an approach to doing so and form an essential part of how the internet works.
To get the IP address in Node.js, we need to include three modules- connect, net, and request-ip. If you do not have these modules installed, let's first install these modules using npm.
Open your command prompt and run the following commands one by one.
npm install connect
npm install net
npm install request-ip
We hope, you have successfully installed these modules. Now, create a file name 'getipaddress.js' and copy and paste the following code.
getipaddress.js
var connect = require('connect');
var http = require('http');
var net = require('net');
var requestIp = require('request-ip');
var app = connect();
app.use(requestIp.mw({ attr : 'getIP' }));
app.use(function(req, res) {
// using our custom attribute that we registered in the middleware
var ip = req.getIP;
console.log(ip);
// returns 4 for IPv4, and 6 for IPv6 and 0 for invalid
var type = net.isIP(ip);
res.end('IP address is ' + ip + ' and is of type IPv' + type + '\n');
});
http.createServer(app).listen(3030);
Explanation of the above code
var app = connect();
The connect() is an extensible HTTP server framework for node using "plugins" known as middleware. The app stores all the added middleware and it is itself a function.
app.use(requestIp.mw({ attr : 'getIP' }));
The 'app.use' is for using the middleware. The all middleware is added as stack and execute each incoming request one by one.
var type = net.isIP(ip);
It checks the input for IP address. If it is, then it returns 0 for invalid IP, 4 for IP version 4 and 6 for IP version 6.
Related Articles
Simple way to send SMTP mail using Node.jsRun Node js Application
Node js HTTP Module
Node js Regular Expression
Node js External HTTP Call
Node js Directory to JSON
PHP User Authentication by IP Address
Get Visitor Information by IP Address in PHP
How To Find IP Address In Python
Python get visitor information by IP address
PHP Getting Document of Remote Address