How to get client IP address using JavaScript and jQuery

Here I will explain How to get client IP address using JavaScript and jQuery. I have to create jQuery Ajax call for finding IP address.

 Introduction:

Today in this article, I will explain How to get client’s IP address using JavaScript and jQuery. Javascript or jQuery is unable to find the IP address of client machine, however with help of jQuery we can create HTTP requests, and server-side languages are able to find your public IP address. So let's get started.

 

Using third-party API(Get public IP Address):

For finding client’s IP address you need any server-side languages means create service on your server or use third-party API.

So there are two types of connection available to get the IP address.

 

Insecure connection HTTP

If you want to find client’s information from a website without SSL certificate, you can rely on ipinfo.io with simple Ajax call.

Write following code:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title></title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script>

        var ipinfo;

        $.getJSON("http://ipinfo.io", function (data) {

            $("#info").html("City: " + data.city + " ,County: " + data.country + " ,IP: " + data.ip + " ,Location: " + data.loc + " ,Organisation: " + data.org + " ,Postal Code: " + data.postal + " ,Region: " + data.region + "")

        })

    </script>

</head>

<body>

    <p>Client's information:</p>

    <p id="info"></p>

</body>

</html>

 

In above code, data object contains localization information for client’s machine.

 

Secure connections HTTPS

To find the client’s information from a website with SSL certificate. You can access ipify service with simple Ajax call.

Write following code:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title></title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script>

            $.getJSON("https://api.ipify.org?format=json", function (data) {

                $("#info").html("IP: " + data.ip + "");

            })

    </script>

</head>

<body>

    <p>Client's information:</p>

    <p id="info"></p>

</body>

</html>

In above code, data object contain information for IP address.

 

If you have your own server, create the private function that returns IP address and calls that service using jQuery Ajax call.

 

 Like this post? Don’t forget to share it!