-1

Could someone please let me know how to get public IP address of the client machine using JavaScript or typescript?

Thanks & Regards, Ajay

ajayg
  • 27
  • 4
  • unfortunately its imposible to achieve it with js on the front end, you can write node js , very simple server to get the user ip from the request and response back with the ip. also you can check this out: https://stackoverflow.com/questions/102605/can-i-perform-a-dns-lookup-hostname-to-ip-address-using-client-side-javascript hopfully it will help – Elna Haim May 25 '22 at 19:13
  • can you share code snippet for node js? – ajayg May 26 '22 at 09:26
  • Yes sure. i will write an answer soon – Elna Haim May 26 '22 at 11:52

1 Answers1

0

This is the most basic configuration. and its only for learning purposes. please take the time to read and learn about running server with node js. the risks and how to protect.


var express = require("express");

var app = express();

app.get("/", (req, res) => {
  console.log(req.ip);
  res.status(200).json({ userIp: req.ip });
});

var listener = app.listen(8080, function () {
  console.log("Listening on port " + listener.address().port);
});

you need to install express. put this code in the app.js.

after running the server any request to '/' will return json with the user ip.

on local host you will get something like ::1 but if you will upload it to a server you will get the right result.

in this case calling loaclhost:8080/ will return the user's ip.

working example here

Elna Haim
  • 545
  • 1
  • 5
  • 19