Q:

How to get a local IP address in Node.js?

belongs to collection: Node.js programming Exercises

0

Getting IP address and type in Node js

How to get a local IP address in Node.js?

In this exercise, you will learn how to get the IP address and its type by using Node js.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

For getting 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 the 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 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< How do I send an email with node mailer in node.js...