Skip to content

How to get client’s IP address using JavaScript?

There’s no built-in solution in JavaScript to get IP Address of the client’s server but there are other cool ways. Using public APIs that returns IP Address is one of the ways (and my favourite too). We can call a publicly available API without any need of additional libraries to fetch IP Address.

Advertisements
const url = "https://api.ipify.org/?format=json"
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

//{"ip":"106.201.178.230"}

Here I use fetch API to retrieve a publicly available HTTP API from Ipify that returns IP Address of the client machine. You can use Axios if you are developing a backend service and you need to find IP address.

Ipinfo’s API returns a lot more details like City, ISP, Country, Zipcode etc.

const url = "https://ipinfo.io/json"
fetch(url)
  .then(response => response.json())
  .then(data => console.log(JSON.stringify(data)));
/*
{
    "ip": "106.206.78.230",
    "city": "Bengaluru",
    "region": "Karnataka",
    "country": "IN",
    "loc": "12.9719,77.5937",
    "org": "AS45609 Bharti Airtel Ltd. AS for GPRS Service",
    "postal": "560002",
    "timezone": "Asia/Kolkata",
    "readme": "https://ipinfo.io/missingauth"
}
*/
Advertisements

Using a external library is another way but I don’t recommend it. Here I use Ipinfo’s JS library to get IP address.

<script type="application/javascript">
    function getip(json){
      alert(json.ip); 
    }
</script>

<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=showIP"></script>
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.