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
address is an address given to a device connected to a network. IP internet protocol
req.socket.remoteAddress
in a Node.js
serverThis 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}`);});
From the code above, we created an port 3000
.
Hence, we can get the IP address of a user by using the req.socket.localAddress
.
req.ip
in an Express.js
serverWhen 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);});
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
.
View a live demo here on my replit.