Easy way to find Public IP Address: Javascript Code
What is my Internet IP Address?
Live example
Finding your IP address…
see the HTML & JS implementation, below
IP Address: HTML and Javascript Code
Finding your public IP address is not a straightforward approach. If you just need the user or visitor’s public IP address after the page load to log or perform any operation then by utilizing a simple JavaScript code snippet you can retrieve the public IP address without relying on paid services.
Use Free API – Unlimited request
You can use the free API provided by ‘ipify.org’ which is absolutely free.
- without any limit, (even millions of requests per minute)
- Opensource (GitHub repository)
- works with both IPv4 and IPv6 addresses
for more details, visit https://www.ipify.org/
Calling ipify API
Open browser and try any API on the address bar
1) https://api.ipify.org/
output: 27.4.142.189
(or)
2)https://api.ipify.org/?format=json
output: {"ip":"27.4.142.189"}
(or)
3) https://api.ipify.org/?format=json&callback=getIP
output: {"ip":"27.4.142.189"}
How to Implement – HTML & JS Script – Samples
Simply use this HTML and javascript to get the public IP address.
See the live example above (used the same JS code)
Sample code 1:
<html>
<br>
<center>
<div>
<h2>What is my Internet IP Address?</h2>
</div>
<br>
<div id="ipaddress">Finding your IP address...</div>
</center>
</html>
<script>
window.addEventListener('load', async function(){
try{
const response = await fetch("https://api.ipify.org/?format=json");
var data = await response.json();
document.getElementById("ipaddress").innerHTML = "<span style='font-size:26px; font-weight:bold'>" + data.ip + "</span><br>Your IP address";
}
catch(err){
document.getElementById("ipaddress").innerText = "Timeout, Please refresh and try again.";
}
});
</script>
Sample code 2:
<html>
<br>
<center>
<div>
<h2>What is my Internet IP Address?</h2>
</div>
<br>
<div id="ipaddress">Finding your IP address...</div>
</center>
</html>
<script>
function getIP(json) {
document.getElementById("ipaddress").innerHTML = "<span style='font-size:26px; font-weight:bold'>" + json.ip + "</span><br>Your IP address";
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Note:
Please use try catch & await.
In rare situation, you might get timeout error because of response delay from API. In such case, use await keyword with try catch block.
See “Sample code 1 implementation, above
In rare situation, you might get timeout error because of response delay from API. In such case, use await keyword with try catch block.
See “Sample code 1 implementation, above