How to get client IP address using JavaScript ?
Last Updated :
17 Jan, 2024
An IP address is a combination of numbers that uniquely identifies one’s system. It’s like a house that has an address to get mail. Similarly, your computer has an address to receive the data from the web.
These are the following approaches by using we can get the client IP address using JavaScript:
By using the ipify
The ipify link can be used with the getJSON() method of jQuery to get the current IP address of the user.
Example: The below code uses ipify for SSL-contained websites(having HTTPS protocol) to get the client’s IP address.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Getting Clients IP
</ title >
< style >
p,
h1 {
color: green;
}
</ style >
< script src =
</ script >
< script >
get the IP Address of user*/
$(document).ready(()=>{
function (data) {
// Displayin IP address on screen
$("#gfg").html(data.ip);
})
});
</ script >
</ head >
< body >
< center >
< h1 >
GeeksforGeeks
</ h1 >
< h3 >
Public IP Address of user is:
</ h3 >
< p id = "gfg" ></ p >
</ center >
</ body >
</ html >
|
Output:
Getting the user’s Public IP address
By using the ipinfo
The ipinfo can also be used to get the IP address in the same way we used the ipify with the get() method by passing a callback function to it.
Example: This code example uses the ipinfo to get the client’s IP address in an alert box.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Getting Clients IP
</ title >
< style >
div{
text-align: center;
}
h1 {
color: green;
}
</ style >
< script src =
</ script >
</ head >
< body >
< div >
< h1 >
GeeksforGeeks
</ h1 >
< h3 >
Getting Client IP address
</ h3 >
< p id = "result" ></ p >
</ div >
< script >
$(document).ready(()=>{
// ipinfo for getting the ip address
function (response) {
$('#result').html(`IP Address: ${response.ip}`)
}, "jsonp");
})
</ script >
</ body >
</ html >
|
Output:
Getting client’s IP address
Note: Sometimes, it will not work on Google Chrome and Internet Explorer for the default setting. It supports Firefox and Microsoft Edge.
Share your thoughts in the comments
Please Login to comment...