Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript program to retrieve clients IP address
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 3rd party 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.
Understanding Client-Side IP Detection
JavaScript running in the browser cannot directly access the client's IP address due to security restrictions. However, we can use external APIs that return the public IP address of the requesting client. These services detect the IP from which the HTTP request originates.
Using "ipify" API
The ipify API (https://www.ipify.org/) is a simple service that returns your public IP address in JSON format. We'll send a GET request using jQuery's $.getJSON() function to retrieve the IP address information.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript program to retrieve client's IP address using ipify</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>
<button onclick="getIPAddress()">Get IP Address</button>
<script>
function getIPAddress() {
$.getJSON("https://api.ipify.org?format=json", function(data) {
document.getElementById("ipAddress").textContent = "Your IP address is: " + data.ip;
}).fail(function() {
document.getElementById("ipAddress").textContent = "Error: Could not retrieve IP address";
});
}
// Auto-load IP address when page loads
$(document).ready(function() {
getIPAddress();
});
</script>
</body>
</html>
Using "ipapi" API
The ipapi service (https://ipapi.co/json/) provides not only the IP address but also additional geolocation information such as country, city, and timezone. This makes it useful for location-based features.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript program to retrieve client's 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 with Location Info</h3>
<div id="ipInfo">Loading IP information...</div>
<script>
$(document).ready(function() {
$.getJSON("https://ipapi.co/json/", function(data) {
const infoHTML = `
<p><strong>IP Address:</strong> ${data.ip}</p>
<p><strong>City:</strong> ${data.city}</p>
<p><strong>Country:</strong> ${data.country_name}</p>
<p><strong>Timezone:</strong> ${data.timezone}</p>
`;
document.getElementById("ipInfo").innerHTML = infoHTML;
}).fail(function() {
document.getElementById("ipInfo").textContent = "Error: Could not retrieve IP information";
});
});
</script>
</body>
</html>
Using Fetch API (Modern Approach)
For modern JavaScript applications, you can use the Fetch API instead of jQuery:
<!DOCTYPE html>
<html>
<head>
<title>Get IP Address using Fetch API</title>
</head>
<body>
<h3>Client IP Address (Using Fetch)</h3>
<p id="result">Loading...</p>
<script>
async function getClientIP() {
try {
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
document.getElementById('result').textContent = `Your IP: ${data.ip}`;
} catch (error) {
document.getElementById('result').textContent = 'Error retrieving IP address';
console.error('Error:', error);
}
}
// Call function when page loads
getClientIP();
</script>
</body>
</html>
API Comparison
| API Service | Response Data | Rate Limit | HTTPS |
|---|---|---|---|
| ipify | IP address only | 1000 requests/hour | Yes |
| ipapi | IP + geolocation data | 1000 requests/month (free) | Yes |
Important Considerations
- CORS: These APIs support Cross-Origin Resource Sharing (CORS), allowing browser requests
- Rate Limits: Free tiers have request limitations; consider caching results
- Privacy: Always inform users when collecting IP addresses
- Accuracy: IP-based location can be inaccurate, especially for mobile users or VPN connections
Conclusion
JavaScript can retrieve client IP addresses through third-party APIs like ipify and ipapi. These services provide reliable IP detection with additional geolocation features, making them suitable for location-based web applications.
