Open In App

How to get client IP address using JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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>
        /* Add "https://api.ipify.org?format=json" to
        get the IP Address of user*/
        $(document).ready(()=>{
            $.getJSON("https://api.ipify.org?format=json",
            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(()=>{
            // Use "https://ipinfo.io" link to use the
            // ipinfo for getting the ip address
            $.getJSON("https://ipinfo.io",
            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.



Last Updated : 17 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads