How to get the IP address of a client in Node.js

Overview

In this shot, we will look at how to get an IP address in Node.js. We can achieve this using a typical Node.js server application and an express server.


The IPinternet protocol address is an address given to a device connected to a network.


Code

How to use req.socket.remoteAddress in a Node.js server

This method is a property of the socket property of the request object.

We can achieve this using the req.socket.remoteAddress or req.ip if you run an Express.js server.

const http = require("http");
const requestListener = function (req, res) {
res.end("Your IP Addresss is: " + req.socket.localAddress);
};
const server = http.createServer(requestListener);
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Explanation

From the code above, we created an HTTPHyperText Transfer Protocol server that sends a response that contains the client’s IP address when the client visits the server on port 3000.

Hence, we can get the IP address of a user by using the req.socket.localAddress.

How to use req.ip in an Express.js server

When you run an Express.js server, it is easy to get the IP address of a client.

Take a look at the code below.

var app = require("express")();
app.get("/", function (req, res) {
console.log(req.socket.remoteAddress);
console.log(req.ip);
res.send("your IP is: " + req.ip);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log("server running on port: " + PORT);
});

Explanation

The code above is similar to the previous one. The only difference is that the latter is created using the Express.js framework of Node.Js.

The easy way to get a client’s IP address is by getting the ip property of the request object, req.

Live code demo

View a live demo here on my replit.