
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieve Client's IP Address in JavaScript
Internet Protocol address, in short, IP address, is a unique address represented by a string of numbers that identifies a device on the internet or a local network. In JavaScript, we can retrieve a client's IP addresses using a 3rd parties API services such as ipify or ipapi. We can then further use this information to track user locations, personalize content based on the location, or implement security measures.
Using "ipify" API
To obtain the client's IP address, we will use a third?party API service (https://www.ipify.org/). We'll send a GET call to the "ipify" API using the $.getJSON() function to get the IP address information. After receiving the IP address, display it in the paragraph element.
Example
A JavaScript program that shows how to retrieve clients IP address is as follows ?
<html> <head> <title>JavaScript program to retrieve clients IP address using ipify</title> </head> <body> <h3>Retrieve Client's IP Address</h3> <p id="ipAddress">Your IP address will appear here.</p> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $.getJSON("https://api.ipify.org?format=json", async function(data) { const res = JSON.stringify(data); const ip = JSON.parse(res).ip; $("#ipAddress").text("Your IP address is: " + ip); }); }); </script> </body> </html>
The result will be similar to the image given below.
Using "ipapi" API
In this approach, the client's IP address will be obtained by sending an AJAX request to the "ipapi" API endpoint (https://ipapi.co/json/) using the jQuery framework. The API offers IP address and geolocation information. We will make a GET request to the "ipapi" API using the $.getJSON() function. Upon receiving the data, the IP address is extracted from the data object and shown in the paragraph element.
Example
In the following JavaScript program, we use the "ipapi" API to find the IP address of the client.
<html> <head> <title>JavaScript program to retrieve clients IP address using ipapi</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h3>Retrieve Client's IP Address</h3> <p id="ipAddress">Your IP address will appear here.</p> <script> $(document).ready(function() { $.getJSON("https://ipapi.co/json/", function(data) { $("#ipAddress").text("Your IP address is: " + data.ip); }); }); </script> </body> </html>
The obtained result will look like the image below ?